PackageManagerService.java revision 9d89543d48b1bd286355f3b2730bee954c8dda1f
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;
91import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
92import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
93import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
94import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
95import static com.android.internal.util.ArrayUtils.appendElement;
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.Binder;
206import android.os.Build;
207import android.os.Bundle;
208import android.os.Debug;
209import android.os.Environment;
210import android.os.Environment.UserEnvironment;
211import android.os.FileUtils;
212import android.os.Handler;
213import android.os.IBinder;
214import android.os.Looper;
215import android.os.Message;
216import android.os.Parcel;
217import android.os.ParcelFileDescriptor;
218import android.os.PatternMatcher;
219import android.os.PersistableBundle;
220import android.os.Process;
221import android.os.RemoteCallbackList;
222import android.os.RemoteException;
223import android.os.ResultReceiver;
224import android.os.SELinux;
225import android.os.ServiceManager;
226import android.os.ShellCallback;
227import android.os.SystemClock;
228import android.os.SystemProperties;
229import android.os.Trace;
230import android.os.UserHandle;
231import android.os.UserManager;
232import android.os.UserManagerInternal;
233import android.os.storage.IStorageManager;
234import android.os.storage.StorageEventListener;
235import android.os.storage.StorageManager;
236import android.os.storage.StorageManagerInternal;
237import android.os.storage.VolumeInfo;
238import android.os.storage.VolumeRecord;
239import android.provider.Settings.Global;
240import android.provider.Settings.Secure;
241import android.security.KeyStore;
242import android.security.SystemKeyStore;
243import android.service.pm.PackageServiceDumpProto;
244import android.system.ErrnoException;
245import android.system.Os;
246import android.text.TextUtils;
247import android.text.format.DateUtils;
248import android.util.ArrayMap;
249import android.util.ArraySet;
250import android.util.Base64;
251import android.util.ByteStringUtils;
252import android.util.DisplayMetrics;
253import android.util.EventLog;
254import android.util.ExceptionUtils;
255import android.util.Log;
256import android.util.LogPrinter;
257import android.util.LongSparseArray;
258import android.util.LongSparseLongArray;
259import android.util.MathUtils;
260import android.util.PackageUtils;
261import android.util.Pair;
262import android.util.PrintStreamPrinter;
263import android.util.Slog;
264import android.util.SparseArray;
265import android.util.SparseBooleanArray;
266import android.util.SparseIntArray;
267import android.util.TimingsTraceLog;
268import android.util.Xml;
269import android.util.jar.StrictJarFile;
270import android.util.proto.ProtoOutputStream;
271import android.view.Display;
272
273import com.android.internal.R;
274import com.android.internal.annotations.GuardedBy;
275import com.android.internal.app.IMediaContainerService;
276import com.android.internal.app.ResolverActivity;
277import com.android.internal.content.NativeLibraryHelper;
278import com.android.internal.content.PackageHelper;
279import com.android.internal.logging.MetricsLogger;
280import com.android.internal.os.IParcelFileDescriptorFactory;
281import com.android.internal.os.SomeArgs;
282import com.android.internal.os.Zygote;
283import com.android.internal.telephony.CarrierAppUtils;
284import com.android.internal.util.ArrayUtils;
285import com.android.internal.util.ConcurrentUtils;
286import com.android.internal.util.DumpUtils;
287import com.android.internal.util.FastXmlSerializer;
288import com.android.internal.util.IndentingPrintWriter;
289import com.android.internal.util.Preconditions;
290import com.android.internal.util.XmlUtils;
291import com.android.server.AttributeCache;
292import com.android.server.DeviceIdleController;
293import com.android.server.EventLogTags;
294import com.android.server.FgThread;
295import com.android.server.IntentResolver;
296import com.android.server.LocalServices;
297import com.android.server.LockGuard;
298import com.android.server.ServiceThread;
299import com.android.server.SystemConfig;
300import com.android.server.SystemServerInitThreadPool;
301import com.android.server.Watchdog;
302import com.android.server.net.NetworkPolicyManagerInternal;
303import com.android.server.pm.Installer.InstallerException;
304import com.android.server.pm.Settings.DatabaseVersion;
305import com.android.server.pm.Settings.VersionInfo;
306import com.android.server.pm.dex.ArtManagerService;
307import com.android.server.pm.dex.DexLogger;
308import com.android.server.pm.dex.DexManager;
309import com.android.server.pm.dex.DexoptOptions;
310import com.android.server.pm.dex.PackageDexUsage;
311import com.android.server.pm.permission.BasePermission;
312import com.android.server.pm.permission.DefaultPermissionGrantPolicy;
313import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback;
314import com.android.server.pm.permission.PermissionManagerInternal;
315import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback;
316import com.android.server.pm.permission.PermissionManagerService;
317import com.android.server.pm.permission.PermissionsState;
318import com.android.server.pm.permission.PermissionsState.PermissionState;
319import com.android.server.security.VerityUtils;
320import com.android.server.storage.DeviceStorageMonitorInternal;
321
322import dalvik.system.CloseGuard;
323import dalvik.system.VMRuntime;
324
325import libcore.io.IoUtils;
326
327import org.xmlpull.v1.XmlPullParser;
328import org.xmlpull.v1.XmlPullParserException;
329import org.xmlpull.v1.XmlSerializer;
330
331import java.io.BufferedOutputStream;
332import java.io.ByteArrayInputStream;
333import java.io.ByteArrayOutputStream;
334import java.io.File;
335import java.io.FileDescriptor;
336import java.io.FileInputStream;
337import java.io.FileOutputStream;
338import java.io.FilenameFilter;
339import java.io.IOException;
340import java.io.PrintWriter;
341import java.lang.annotation.Retention;
342import java.lang.annotation.RetentionPolicy;
343import java.nio.charset.StandardCharsets;
344import java.security.DigestException;
345import java.security.DigestInputStream;
346import java.security.MessageDigest;
347import java.security.NoSuchAlgorithmException;
348import java.security.PublicKey;
349import java.security.SecureRandom;
350import java.security.cert.CertificateException;
351import java.util.ArrayList;
352import java.util.Arrays;
353import java.util.Collection;
354import java.util.Collections;
355import java.util.Comparator;
356import java.util.HashMap;
357import java.util.HashSet;
358import java.util.Iterator;
359import java.util.LinkedHashSet;
360import java.util.List;
361import java.util.Map;
362import java.util.Objects;
363import java.util.Set;
364import java.util.concurrent.CountDownLatch;
365import java.util.concurrent.Future;
366import java.util.concurrent.TimeUnit;
367import java.util.concurrent.atomic.AtomicBoolean;
368import java.util.concurrent.atomic.AtomicInteger;
369
370/**
371 * Keep track of all those APKs everywhere.
372 * <p>
373 * Internally there are two important locks:
374 * <ul>
375 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
376 * and other related state. It is a fine-grained lock that should only be held
377 * momentarily, as it's one of the most contended locks in the system.
378 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
379 * operations typically involve heavy lifting of application data on disk. Since
380 * {@code installd} is single-threaded, and it's operations can often be slow,
381 * this lock should never be acquired while already holding {@link #mPackages}.
382 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
383 * holding {@link #mInstallLock}.
384 * </ul>
385 * Many internal methods rely on the caller to hold the appropriate locks, and
386 * this contract is expressed through method name suffixes:
387 * <ul>
388 * <li>fooLI(): the caller must hold {@link #mInstallLock}
389 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
390 * being modified must be frozen
391 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
392 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
393 * </ul>
394 * <p>
395 * Because this class is very central to the platform's security; please run all
396 * CTS and unit tests whenever making modifications:
397 *
398 * <pre>
399 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
400 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
401 * </pre>
402 */
403public class PackageManagerService extends IPackageManager.Stub
404        implements PackageSender {
405    static final String TAG = "PackageManager";
406    public static final boolean DEBUG_SETTINGS = false;
407    static final boolean DEBUG_PREFERRED = false;
408    static final boolean DEBUG_UPGRADE = false;
409    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
410    private static final boolean DEBUG_BACKUP = false;
411    public static final boolean DEBUG_INSTALL = false;
412    public static final boolean DEBUG_REMOVE = true;
413    private static final boolean DEBUG_BROADCASTS = false;
414    private static final boolean DEBUG_SHOW_INFO = false;
415    private static final boolean DEBUG_PACKAGE_INFO = false;
416    private static final boolean DEBUG_INTENT_MATCHING = false;
417    public static final boolean DEBUG_PACKAGE_SCANNING = false;
418    private static final boolean DEBUG_VERIFY = false;
419    private static final boolean DEBUG_FILTERS = false;
420    public static final boolean DEBUG_PERMISSIONS = false;
421    private static final boolean DEBUG_SHARED_LIBRARIES = false;
422    public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
423
424    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
425    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
426    // user, but by default initialize to this.
427    public static final boolean DEBUG_DEXOPT = false;
428
429    private static final boolean DEBUG_ABI_SELECTION = false;
430    private static final boolean DEBUG_INSTANT = Build.IS_DEBUGGABLE;
431    private static final boolean DEBUG_TRIAGED_MISSING = false;
432    private static final boolean DEBUG_APP_DATA = false;
433
434    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
435    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
436
437    private static final boolean HIDE_EPHEMERAL_APIS = false;
438
439    private static final boolean ENABLE_FREE_CACHE_V2 =
440            SystemProperties.getBoolean("fw.free_cache_v2", true);
441
442    private static final int RADIO_UID = Process.PHONE_UID;
443    private static final int LOG_UID = Process.LOG_UID;
444    private static final int NFC_UID = Process.NFC_UID;
445    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
446    private static final int SHELL_UID = Process.SHELL_UID;
447    private static final int SE_UID = Process.SE_UID;
448
449    // Suffix used during package installation when copying/moving
450    // package apks to install directory.
451    private static final String INSTALL_PACKAGE_SUFFIX = "-";
452
453    static final int SCAN_NO_DEX = 1<<0;
454    static final int SCAN_UPDATE_SIGNATURE = 1<<1;
455    static final int SCAN_NEW_INSTALL = 1<<2;
456    static final int SCAN_UPDATE_TIME = 1<<3;
457    static final int SCAN_BOOTING = 1<<4;
458    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<6;
459    static final int SCAN_REQUIRE_KNOWN = 1<<7;
460    static final int SCAN_MOVE = 1<<8;
461    static final int SCAN_INITIAL = 1<<9;
462    static final int SCAN_CHECK_ONLY = 1<<10;
463    static final int SCAN_DONT_KILL_APP = 1<<11;
464    static final int SCAN_IGNORE_FROZEN = 1<<12;
465    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<13;
466    static final int SCAN_AS_INSTANT_APP = 1<<14;
467    static final int SCAN_AS_FULL_APP = 1<<15;
468    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<16;
469    static final int SCAN_AS_SYSTEM = 1<<17;
470    static final int SCAN_AS_PRIVILEGED = 1<<18;
471    static final int SCAN_AS_OEM = 1<<19;
472    static final int SCAN_AS_VENDOR = 1<<20;
473    static final int SCAN_AS_PRODUCT = 1<<21;
474
475    @IntDef(flag = true, prefix = { "SCAN_" }, value = {
476            SCAN_NO_DEX,
477            SCAN_UPDATE_SIGNATURE,
478            SCAN_NEW_INSTALL,
479            SCAN_UPDATE_TIME,
480            SCAN_BOOTING,
481            SCAN_DELETE_DATA_ON_FAILURES,
482            SCAN_REQUIRE_KNOWN,
483            SCAN_MOVE,
484            SCAN_INITIAL,
485            SCAN_CHECK_ONLY,
486            SCAN_DONT_KILL_APP,
487            SCAN_IGNORE_FROZEN,
488            SCAN_FIRST_BOOT_OR_UPGRADE,
489            SCAN_AS_INSTANT_APP,
490            SCAN_AS_FULL_APP,
491            SCAN_AS_VIRTUAL_PRELOAD,
492    })
493    @Retention(RetentionPolicy.SOURCE)
494    public @interface ScanFlags {}
495
496    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
497    /** Extension of the compressed packages */
498    public final static String COMPRESSED_EXTENSION = ".gz";
499    /** Suffix of stub packages on the system partition */
500    public final static String STUB_SUFFIX = "-Stub";
501
502    private static final int[] EMPTY_INT_ARRAY = new int[0];
503
504    private static final int TYPE_UNKNOWN = 0;
505    private static final int TYPE_ACTIVITY = 1;
506    private static final int TYPE_RECEIVER = 2;
507    private static final int TYPE_SERVICE = 3;
508    private static final int TYPE_PROVIDER = 4;
509    @IntDef(prefix = { "TYPE_" }, value = {
510            TYPE_UNKNOWN,
511            TYPE_ACTIVITY,
512            TYPE_RECEIVER,
513            TYPE_SERVICE,
514            TYPE_PROVIDER,
515    })
516    @Retention(RetentionPolicy.SOURCE)
517    public @interface ComponentType {}
518
519    /**
520     * Timeout (in milliseconds) after which the watchdog should declare that
521     * our handler thread is wedged.  The usual default for such things is one
522     * minute but we sometimes do very lengthy I/O operations on this thread,
523     * such as installing multi-gigabyte applications, so ours needs to be longer.
524     */
525    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
526
527    /**
528     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
529     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
530     * settings entry if available, otherwise we use the hardcoded default.  If it's been
531     * more than this long since the last fstrim, we force one during the boot sequence.
532     *
533     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
534     * one gets run at the next available charging+idle time.  This final mandatory
535     * no-fstrim check kicks in only of the other scheduling criteria is never met.
536     */
537    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
538
539    /**
540     * Whether verification is enabled by default.
541     */
542    private static final boolean DEFAULT_VERIFY_ENABLE = true;
543
544    /**
545     * The default maximum time to wait for the verification agent to return in
546     * milliseconds.
547     */
548    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
549
550    /**
551     * The default response for package verification timeout.
552     *
553     * This can be either PackageManager.VERIFICATION_ALLOW or
554     * PackageManager.VERIFICATION_REJECT.
555     */
556    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
557
558    public static final String PLATFORM_PACKAGE_NAME = "android";
559
560    public static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
561
562    public static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
563            DEFAULT_CONTAINER_PACKAGE,
564            "com.android.defcontainer.DefaultContainerService");
565
566    private static final String KILL_APP_REASON_GIDS_CHANGED =
567            "permission grant or revoke changed gids";
568
569    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
570            "permissions revoked";
571
572    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
573
574    private static final String PACKAGE_SCHEME = "package";
575
576    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
577
578    private static final String PRODUCT_OVERLAY_DIR = "/product/overlay";
579
580    private static final String PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB = "pm.dexopt.priv-apps-oob";
581
582    /** Canonical intent used to identify what counts as a "web browser" app */
583    private static final Intent sBrowserIntent;
584    static {
585        sBrowserIntent = new Intent();
586        sBrowserIntent.setAction(Intent.ACTION_VIEW);
587        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
588        sBrowserIntent.setData(Uri.parse("http:"));
589        sBrowserIntent.addFlags(Intent.FLAG_IGNORE_EPHEMERAL);
590    }
591
592    /**
593     * The set of all protected actions [i.e. those actions for which a high priority
594     * intent filter is disallowed].
595     */
596    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
597    static {
598        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
599        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
600        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
601        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
602    }
603
604    // Compilation reasons.
605    public static final int REASON_UNKNOWN = -1;
606    public static final int REASON_FIRST_BOOT = 0;
607    public static final int REASON_BOOT = 1;
608    public static final int REASON_INSTALL = 2;
609    public static final int REASON_BACKGROUND_DEXOPT = 3;
610    public static final int REASON_AB_OTA = 4;
611    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
612    public static final int REASON_SHARED = 6;
613
614    public static final int REASON_LAST = REASON_SHARED;
615
616    /**
617     * Version number for the package parser cache. Increment this whenever the format or
618     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
619     */
620    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
621
622    /**
623     * Whether the package parser cache is enabled.
624     */
625    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
626
627    /**
628     * Permissions required in order to receive instant application lifecycle broadcasts.
629     */
630    private static final String[] INSTANT_APP_BROADCAST_PERMISSION =
631            new String[] { android.Manifest.permission.ACCESS_INSTANT_APPS };
632
633    final ServiceThread mHandlerThread;
634
635    final PackageHandler mHandler;
636
637    private final ProcessLoggingHandler mProcessLoggingHandler;
638
639    /**
640     * Messages for {@link #mHandler} that need to wait for system ready before
641     * being dispatched.
642     */
643    private ArrayList<Message> mPostSystemReadyMessages;
644
645    final int mSdkVersion = Build.VERSION.SDK_INT;
646
647    final Context mContext;
648    final boolean mFactoryTest;
649    final boolean mOnlyCore;
650    final DisplayMetrics mMetrics;
651    final int mDefParseFlags;
652    final String[] mSeparateProcesses;
653    final boolean mIsUpgrade;
654    final boolean mIsPreNUpgrade;
655    final boolean mIsPreNMR1Upgrade;
656
657    // Have we told the Activity Manager to whitelist the default container service by uid yet?
658    @GuardedBy("mPackages")
659    boolean mDefaultContainerWhitelisted = false;
660
661    @GuardedBy("mPackages")
662    private boolean mDexOptDialogShown;
663
664    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
665    // LOCK HELD.  Can be called with mInstallLock held.
666    @GuardedBy("mInstallLock")
667    final Installer mInstaller;
668
669    /** Directory where installed applications are stored */
670    private static final File sAppInstallDir =
671            new File(Environment.getDataDirectory(), "app");
672    /** Directory where installed application's 32-bit native libraries are copied. */
673    private static final File sAppLib32InstallDir =
674            new File(Environment.getDataDirectory(), "app-lib");
675    /** Directory where code and non-resource assets of forward-locked applications are stored */
676    private static final File sDrmAppPrivateInstallDir =
677            new File(Environment.getDataDirectory(), "app-private");
678
679    // ----------------------------------------------------------------
680
681    // Lock for state used when installing and doing other long running
682    // operations.  Methods that must be called with this lock held have
683    // the suffix "LI".
684    final Object mInstallLock = new Object();
685
686    // ----------------------------------------------------------------
687
688    // Keys are String (package name), values are Package.  This also serves
689    // as the lock for the global state.  Methods that must be called with
690    // this lock held have the prefix "LP".
691    @GuardedBy("mPackages")
692    final ArrayMap<String, PackageParser.Package> mPackages =
693            new ArrayMap<String, PackageParser.Package>();
694
695    final ArrayMap<String, Set<String>> mKnownCodebase =
696            new ArrayMap<String, Set<String>>();
697
698    // Keys are isolated uids and values are the uid of the application
699    // that created the isolated proccess.
700    @GuardedBy("mPackages")
701    final SparseIntArray mIsolatedOwners = new SparseIntArray();
702
703    /**
704     * Tracks new system packages [received in an OTA] that we expect to
705     * find updated user-installed versions. Keys are package name, values
706     * are package location.
707     */
708    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
709    /**
710     * Tracks high priority intent filters for protected actions. During boot, certain
711     * filter actions are protected and should never be allowed to have a high priority
712     * intent filter for them. However, there is one, and only one exception -- the
713     * setup wizard. It must be able to define a high priority intent filter for these
714     * actions to ensure there are no escapes from the wizard. We need to delay processing
715     * of these during boot as we need to look at all of the system packages in order
716     * to know which component is the setup wizard.
717     */
718    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
719    /**
720     * Whether or not processing protected filters should be deferred.
721     */
722    private boolean mDeferProtectedFilters = true;
723
724    /**
725     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
726     */
727    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
728    /**
729     * Whether or not system app permissions should be promoted from install to runtime.
730     */
731    boolean mPromoteSystemApps;
732
733    @GuardedBy("mPackages")
734    final Settings mSettings;
735
736    /**
737     * Set of package names that are currently "frozen", which means active
738     * surgery is being done on the code/data for that package. The platform
739     * will refuse to launch frozen packages to avoid race conditions.
740     *
741     * @see PackageFreezer
742     */
743    @GuardedBy("mPackages")
744    final ArraySet<String> mFrozenPackages = new ArraySet<>();
745
746    final ProtectedPackages mProtectedPackages;
747
748    @GuardedBy("mLoadedVolumes")
749    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
750
751    boolean mFirstBoot;
752
753    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
754
755    @GuardedBy("mAvailableFeatures")
756    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
757
758    private final InstantAppRegistry mInstantAppRegistry;
759
760    @GuardedBy("mPackages")
761    int mChangedPackagesSequenceNumber;
762    /**
763     * List of changed [installed, removed or updated] packages.
764     * mapping from user id -> sequence number -> package name
765     */
766    @GuardedBy("mPackages")
767    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
768    /**
769     * The sequence number of the last change to a package.
770     * mapping from user id -> package name -> sequence number
771     */
772    @GuardedBy("mPackages")
773    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
774
775    @GuardedBy("mPackages")
776    final private ArraySet<PackageListObserver> mPackageListObservers = new ArraySet<>();
777
778    class PackageParserCallback implements PackageParser.Callback {
779        @Override public final boolean hasFeature(String feature) {
780            return PackageManagerService.this.hasSystemFeature(feature, 0);
781        }
782
783        final List<PackageParser.Package> getStaticOverlayPackages(
784                Collection<PackageParser.Package> allPackages, String targetPackageName) {
785            if ("android".equals(targetPackageName)) {
786                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
787                // native AssetManager.
788                return null;
789            }
790
791            List<PackageParser.Package> overlayPackages = null;
792            for (PackageParser.Package p : allPackages) {
793                if (targetPackageName.equals(p.mOverlayTarget) && p.mOverlayIsStatic) {
794                    if (overlayPackages == null) {
795                        overlayPackages = new ArrayList<PackageParser.Package>();
796                    }
797                    overlayPackages.add(p);
798                }
799            }
800            if (overlayPackages != null) {
801                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
802                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
803                        return p1.mOverlayPriority - p2.mOverlayPriority;
804                    }
805                };
806                Collections.sort(overlayPackages, cmp);
807            }
808            return overlayPackages;
809        }
810
811        final String[] getStaticOverlayPaths(List<PackageParser.Package> overlayPackages,
812                String targetPath) {
813            if (overlayPackages == null || overlayPackages.isEmpty()) {
814                return null;
815            }
816            List<String> overlayPathList = null;
817            for (PackageParser.Package overlayPackage : overlayPackages) {
818                if (targetPath == null) {
819                    if (overlayPathList == null) {
820                        overlayPathList = new ArrayList<String>();
821                    }
822                    overlayPathList.add(overlayPackage.baseCodePath);
823                    continue;
824                }
825
826                try {
827                    // Creates idmaps for system to parse correctly the Android manifest of the
828                    // target package.
829                    //
830                    // OverlayManagerService will update each of them with a correct gid from its
831                    // target package app id.
832                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
833                            UserHandle.getSharedAppGid(
834                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
835                    if (overlayPathList == null) {
836                        overlayPathList = new ArrayList<String>();
837                    }
838                    overlayPathList.add(overlayPackage.baseCodePath);
839                } catch (InstallerException e) {
840                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
841                            overlayPackage.baseCodePath);
842                }
843            }
844            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
845        }
846
847        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
848            List<PackageParser.Package> overlayPackages;
849            synchronized (mInstallLock) {
850                synchronized (mPackages) {
851                    overlayPackages = getStaticOverlayPackages(
852                            mPackages.values(), targetPackageName);
853                }
854                // It is safe to keep overlayPackages without holding mPackages because static overlay
855                // packages can't be uninstalled or disabled.
856                return getStaticOverlayPaths(overlayPackages, targetPath);
857            }
858        }
859
860        @Override public final String[] getOverlayApks(String targetPackageName) {
861            return getStaticOverlayPaths(targetPackageName, null);
862        }
863
864        @Override public final String[] getOverlayPaths(String targetPackageName,
865                String targetPath) {
866            return getStaticOverlayPaths(targetPackageName, targetPath);
867        }
868    }
869
870    class ParallelPackageParserCallback extends PackageParserCallback {
871        List<PackageParser.Package> mOverlayPackages = null;
872
873        void findStaticOverlayPackages() {
874            synchronized (mPackages) {
875                for (PackageParser.Package p : mPackages.values()) {
876                    if (p.mOverlayIsStatic) {
877                        if (mOverlayPackages == null) {
878                            mOverlayPackages = new ArrayList<PackageParser.Package>();
879                        }
880                        mOverlayPackages.add(p);
881                    }
882                }
883            }
884        }
885
886        @Override
887        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
888            // We can trust mOverlayPackages without holding mPackages because package uninstall
889            // can't happen while running parallel parsing.
890            // And we can call mInstaller inside getStaticOverlayPaths without holding mInstallLock
891            // because mInstallLock is held before running parallel parsing.
892            // Moreover holding mPackages or mInstallLock on each parsing thread causes dead-lock.
893            return mOverlayPackages == null ? null :
894                    getStaticOverlayPaths(
895                            getStaticOverlayPackages(mOverlayPackages, targetPackageName),
896                            targetPath);
897        }
898    }
899
900    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
901    final ParallelPackageParserCallback mParallelPackageParserCallback =
902            new ParallelPackageParserCallback();
903
904    public static final class SharedLibraryEntry {
905        public final @Nullable String path;
906        public final @Nullable String apk;
907        public final @NonNull SharedLibraryInfo info;
908
909        SharedLibraryEntry(String _path, String _apk, String name, long version, int type,
910                String declaringPackageName, long declaringPackageVersionCode) {
911            path = _path;
912            apk = _apk;
913            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
914                    declaringPackageName, declaringPackageVersionCode), null);
915        }
916    }
917
918    // Currently known shared libraries.
919    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
920    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
921            new ArrayMap<>();
922
923    // All available activities, for your resolving pleasure.
924    final ActivityIntentResolver mActivities =
925            new ActivityIntentResolver();
926
927    // All available receivers, for your resolving pleasure.
928    final ActivityIntentResolver mReceivers =
929            new ActivityIntentResolver();
930
931    // All available services, for your resolving pleasure.
932    final ServiceIntentResolver mServices = new ServiceIntentResolver();
933
934    // All available providers, for your resolving pleasure.
935    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
936
937    // Mapping from provider base names (first directory in content URI codePath)
938    // to the provider information.
939    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
940            new ArrayMap<String, PackageParser.Provider>();
941
942    // Mapping from instrumentation class names to info about them.
943    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
944            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
945
946    // Packages whose data we have transfered into another package, thus
947    // should no longer exist.
948    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
949
950    // Broadcast actions that are only available to the system.
951    @GuardedBy("mProtectedBroadcasts")
952    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
953
954    /** List of packages waiting for verification. */
955    final SparseArray<PackageVerificationState> mPendingVerification
956            = new SparseArray<PackageVerificationState>();
957
958    final PackageInstallerService mInstallerService;
959
960    final ArtManagerService mArtManagerService;
961
962    private final PackageDexOptimizer mPackageDexOptimizer;
963    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
964    // is used by other apps).
965    private final DexManager mDexManager;
966
967    private AtomicInteger mNextMoveId = new AtomicInteger();
968    private final MoveCallbacks mMoveCallbacks;
969
970    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
971
972    // Cache of users who need badging.
973    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
974
975    /** Token for keys in mPendingVerification. */
976    private int mPendingVerificationToken = 0;
977
978    volatile boolean mSystemReady;
979    volatile boolean mSafeMode;
980    volatile boolean mHasSystemUidErrors;
981    private volatile boolean mWebInstantAppsDisabled;
982
983    ApplicationInfo mAndroidApplication;
984    final ActivityInfo mResolveActivity = new ActivityInfo();
985    final ResolveInfo mResolveInfo = new ResolveInfo();
986    ComponentName mResolveComponentName;
987    PackageParser.Package mPlatformPackage;
988    ComponentName mCustomResolverComponentName;
989
990    boolean mResolverReplaced = false;
991
992    private final @Nullable ComponentName mIntentFilterVerifierComponent;
993    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
994
995    private int mIntentFilterVerificationToken = 0;
996
997    /** The service connection to the ephemeral resolver */
998    final InstantAppResolverConnection mInstantAppResolverConnection;
999    /** Component used to show resolver settings for Instant Apps */
1000    final ComponentName mInstantAppResolverSettingsComponent;
1001
1002    /** Activity used to install instant applications */
1003    ActivityInfo mInstantAppInstallerActivity;
1004    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
1005
1006    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
1007            = new SparseArray<IntentFilterVerificationState>();
1008
1009    // TODO remove this and go through mPermissonManager directly
1010    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1011    private final PermissionManagerInternal mPermissionManager;
1012
1013    // List of packages names to keep cached, even if they are uninstalled for all users
1014    private List<String> mKeepUninstalledPackages;
1015
1016    private UserManagerInternal mUserManagerInternal;
1017    private ActivityManagerInternal mActivityManagerInternal;
1018
1019    private DeviceIdleController.LocalService mDeviceIdleController;
1020
1021    private File mCacheDir;
1022
1023    private Future<?> mPrepareAppDataFuture;
1024
1025    private static class IFVerificationParams {
1026        PackageParser.Package pkg;
1027        boolean replacing;
1028        int userId;
1029        int verifierUid;
1030
1031        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1032                int _userId, int _verifierUid) {
1033            pkg = _pkg;
1034            replacing = _replacing;
1035            userId = _userId;
1036            replacing = _replacing;
1037            verifierUid = _verifierUid;
1038        }
1039    }
1040
1041    private interface IntentFilterVerifier<T extends IntentFilter> {
1042        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1043                                               T filter, String packageName);
1044        void startVerifications(int userId);
1045        void receiveVerificationResponse(int verificationId);
1046    }
1047
1048    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1049        private Context mContext;
1050        private ComponentName mIntentFilterVerifierComponent;
1051        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1052
1053        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1054            mContext = context;
1055            mIntentFilterVerifierComponent = verifierComponent;
1056        }
1057
1058        private String getDefaultScheme() {
1059            return IntentFilter.SCHEME_HTTPS;
1060        }
1061
1062        @Override
1063        public void startVerifications(int userId) {
1064            // Launch verifications requests
1065            int count = mCurrentIntentFilterVerifications.size();
1066            for (int n=0; n<count; n++) {
1067                int verificationId = mCurrentIntentFilterVerifications.get(n);
1068                final IntentFilterVerificationState ivs =
1069                        mIntentFilterVerificationStates.get(verificationId);
1070
1071                String packageName = ivs.getPackageName();
1072
1073                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1074                final int filterCount = filters.size();
1075                ArraySet<String> domainsSet = new ArraySet<>();
1076                for (int m=0; m<filterCount; m++) {
1077                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1078                    domainsSet.addAll(filter.getHostsList());
1079                }
1080                synchronized (mPackages) {
1081                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1082                            packageName, domainsSet) != null) {
1083                        scheduleWriteSettingsLocked();
1084                    }
1085                }
1086                sendVerificationRequest(verificationId, ivs);
1087            }
1088            mCurrentIntentFilterVerifications.clear();
1089        }
1090
1091        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1092            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1093            verificationIntent.putExtra(
1094                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1095                    verificationId);
1096            verificationIntent.putExtra(
1097                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1098                    getDefaultScheme());
1099            verificationIntent.putExtra(
1100                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1101                    ivs.getHostsString());
1102            verificationIntent.putExtra(
1103                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1104                    ivs.getPackageName());
1105            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1106            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1107
1108            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1109            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1110                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1111                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1112
1113            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1114            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1115                    "Sending IntentFilter verification broadcast");
1116        }
1117
1118        public void receiveVerificationResponse(int verificationId) {
1119            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1120
1121            final boolean verified = ivs.isVerified();
1122
1123            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1124            final int count = filters.size();
1125            if (DEBUG_DOMAIN_VERIFICATION) {
1126                Slog.i(TAG, "Received verification response " + verificationId
1127                        + " for " + count + " filters, verified=" + verified);
1128            }
1129            for (int n=0; n<count; n++) {
1130                PackageParser.ActivityIntentInfo filter = filters.get(n);
1131                filter.setVerified(verified);
1132
1133                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1134                        + " verified with result:" + verified + " and hosts:"
1135                        + ivs.getHostsString());
1136            }
1137
1138            mIntentFilterVerificationStates.remove(verificationId);
1139
1140            final String packageName = ivs.getPackageName();
1141            IntentFilterVerificationInfo ivi = null;
1142
1143            synchronized (mPackages) {
1144                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1145            }
1146            if (ivi == null) {
1147                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1148                        + verificationId + " packageName:" + packageName);
1149                return;
1150            }
1151            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1152                    "Updating IntentFilterVerificationInfo for package " + packageName
1153                            +" verificationId:" + verificationId);
1154
1155            synchronized (mPackages) {
1156                if (verified) {
1157                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1158                } else {
1159                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1160                }
1161                scheduleWriteSettingsLocked();
1162
1163                final int userId = ivs.getUserId();
1164                if (userId != UserHandle.USER_ALL) {
1165                    final int userStatus =
1166                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1167
1168                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1169                    boolean needUpdate = false;
1170
1171                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1172                    // already been set by the User thru the Disambiguation dialog
1173                    switch (userStatus) {
1174                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1175                            if (verified) {
1176                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1177                            } else {
1178                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1179                            }
1180                            needUpdate = true;
1181                            break;
1182
1183                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1184                            if (verified) {
1185                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1186                                needUpdate = true;
1187                            }
1188                            break;
1189
1190                        default:
1191                            // Nothing to do
1192                    }
1193
1194                    if (needUpdate) {
1195                        mSettings.updateIntentFilterVerificationStatusLPw(
1196                                packageName, updatedStatus, userId);
1197                        scheduleWritePackageRestrictionsLocked(userId);
1198                    }
1199                }
1200            }
1201        }
1202
1203        @Override
1204        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1205                    ActivityIntentInfo filter, String packageName) {
1206            if (!hasValidDomains(filter)) {
1207                return false;
1208            }
1209            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1210            if (ivs == null) {
1211                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1212                        packageName);
1213            }
1214            if (DEBUG_DOMAIN_VERIFICATION) {
1215                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1216            }
1217            ivs.addFilter(filter);
1218            return true;
1219        }
1220
1221        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1222                int userId, int verificationId, String packageName) {
1223            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1224                    verifierUid, userId, packageName);
1225            ivs.setPendingState();
1226            synchronized (mPackages) {
1227                mIntentFilterVerificationStates.append(verificationId, ivs);
1228                mCurrentIntentFilterVerifications.add(verificationId);
1229            }
1230            return ivs;
1231        }
1232    }
1233
1234    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1235        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1236                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1237                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1238    }
1239
1240    // Set of pending broadcasts for aggregating enable/disable of components.
1241    static class PendingPackageBroadcasts {
1242        // for each user id, a map of <package name -> components within that package>
1243        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1244
1245        public PendingPackageBroadcasts() {
1246            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1247        }
1248
1249        public ArrayList<String> get(int userId, String packageName) {
1250            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1251            return packages.get(packageName);
1252        }
1253
1254        public void put(int userId, String packageName, ArrayList<String> components) {
1255            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1256            packages.put(packageName, components);
1257        }
1258
1259        public void remove(int userId, String packageName) {
1260            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1261            if (packages != null) {
1262                packages.remove(packageName);
1263            }
1264        }
1265
1266        public void remove(int userId) {
1267            mUidMap.remove(userId);
1268        }
1269
1270        public int userIdCount() {
1271            return mUidMap.size();
1272        }
1273
1274        public int userIdAt(int n) {
1275            return mUidMap.keyAt(n);
1276        }
1277
1278        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1279            return mUidMap.get(userId);
1280        }
1281
1282        public int size() {
1283            // total number of pending broadcast entries across all userIds
1284            int num = 0;
1285            for (int i = 0; i< mUidMap.size(); i++) {
1286                num += mUidMap.valueAt(i).size();
1287            }
1288            return num;
1289        }
1290
1291        public void clear() {
1292            mUidMap.clear();
1293        }
1294
1295        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1296            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1297            if (map == null) {
1298                map = new ArrayMap<String, ArrayList<String>>();
1299                mUidMap.put(userId, map);
1300            }
1301            return map;
1302        }
1303    }
1304    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1305
1306    // Service Connection to remote media container service to copy
1307    // package uri's from external media onto secure containers
1308    // or internal storage.
1309    private IMediaContainerService mContainerService = null;
1310
1311    static final int SEND_PENDING_BROADCAST = 1;
1312    static final int MCS_BOUND = 3;
1313    static final int END_COPY = 4;
1314    static final int INIT_COPY = 5;
1315    static final int MCS_UNBIND = 6;
1316    static final int START_CLEANING_PACKAGE = 7;
1317    static final int FIND_INSTALL_LOC = 8;
1318    static final int POST_INSTALL = 9;
1319    static final int MCS_RECONNECT = 10;
1320    static final int MCS_GIVE_UP = 11;
1321    static final int WRITE_SETTINGS = 13;
1322    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1323    static final int PACKAGE_VERIFIED = 15;
1324    static final int CHECK_PENDING_VERIFICATION = 16;
1325    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1326    static final int INTENT_FILTER_VERIFIED = 18;
1327    static final int WRITE_PACKAGE_LIST = 19;
1328    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1329    static final int DEF_CONTAINER_BIND = 21;
1330
1331    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1332
1333    // Delay time in millisecs
1334    static final int BROADCAST_DELAY = 10 * 1000;
1335
1336    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1337            2 * 60 * 60 * 1000L; /* two hours */
1338
1339    static UserManagerService sUserManager;
1340
1341    // Stores a list of users whose package restrictions file needs to be updated
1342    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1343
1344    final private DefaultContainerConnection mDefContainerConn =
1345            new DefaultContainerConnection();
1346    class DefaultContainerConnection implements ServiceConnection {
1347        public void onServiceConnected(ComponentName name, IBinder service) {
1348            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1349            final IMediaContainerService imcs = IMediaContainerService.Stub
1350                    .asInterface(Binder.allowBlocking(service));
1351            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1352        }
1353
1354        public void onServiceDisconnected(ComponentName name) {
1355            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1356        }
1357    }
1358
1359    // Recordkeeping of restore-after-install operations that are currently in flight
1360    // between the Package Manager and the Backup Manager
1361    static class PostInstallData {
1362        public InstallArgs args;
1363        public PackageInstalledInfo res;
1364
1365        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1366            args = _a;
1367            res = _r;
1368        }
1369    }
1370
1371    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1372    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1373
1374    // XML tags for backup/restore of various bits of state
1375    private static final String TAG_PREFERRED_BACKUP = "pa";
1376    private static final String TAG_DEFAULT_APPS = "da";
1377    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1378
1379    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1380    private static final String TAG_ALL_GRANTS = "rt-grants";
1381    private static final String TAG_GRANT = "grant";
1382    private static final String ATTR_PACKAGE_NAME = "pkg";
1383
1384    private static final String TAG_PERMISSION = "perm";
1385    private static final String ATTR_PERMISSION_NAME = "name";
1386    private static final String ATTR_IS_GRANTED = "g";
1387    private static final String ATTR_USER_SET = "set";
1388    private static final String ATTR_USER_FIXED = "fixed";
1389    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1390
1391    // System/policy permission grants are not backed up
1392    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1393            FLAG_PERMISSION_POLICY_FIXED
1394            | FLAG_PERMISSION_SYSTEM_FIXED
1395            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1396
1397    // And we back up these user-adjusted states
1398    private static final int USER_RUNTIME_GRANT_MASK =
1399            FLAG_PERMISSION_USER_SET
1400            | FLAG_PERMISSION_USER_FIXED
1401            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1402
1403    final @Nullable String mRequiredVerifierPackage;
1404    final @NonNull String mRequiredInstallerPackage;
1405    final @NonNull String mRequiredUninstallerPackage;
1406    final @Nullable String mSetupWizardPackage;
1407    final @Nullable String mStorageManagerPackage;
1408    final @Nullable String mSystemTextClassifierPackage;
1409    final @NonNull String mServicesSystemSharedLibraryPackageName;
1410    final @NonNull String mSharedSystemSharedLibraryPackageName;
1411
1412    private final PackageUsage mPackageUsage = new PackageUsage();
1413    private final CompilerStats mCompilerStats = new CompilerStats();
1414
1415    class PackageHandler extends Handler {
1416        private boolean mBound = false;
1417        final ArrayList<HandlerParams> mPendingInstalls =
1418            new ArrayList<HandlerParams>();
1419
1420        private boolean connectToService() {
1421            if (DEBUG_INSTALL) Log.i(TAG, "Trying to bind to DefaultContainerService");
1422            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1423            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1424            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1425                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1426                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1427                mBound = true;
1428                return true;
1429            }
1430            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1431            return false;
1432        }
1433
1434        private void disconnectService() {
1435            mContainerService = null;
1436            mBound = false;
1437            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1438            mContext.unbindService(mDefContainerConn);
1439            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1440        }
1441
1442        PackageHandler(Looper looper) {
1443            super(looper);
1444        }
1445
1446        public void handleMessage(Message msg) {
1447            try {
1448                doHandleMessage(msg);
1449            } finally {
1450                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1451            }
1452        }
1453
1454        void doHandleMessage(Message msg) {
1455            switch (msg.what) {
1456                case DEF_CONTAINER_BIND:
1457                    if (!mBound) {
1458                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "earlyBindingMCS",
1459                                System.identityHashCode(mHandler));
1460                        if (!connectToService()) {
1461                            Slog.e(TAG, "Failed to bind to media container service");
1462                        }
1463                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "earlyBindingMCS",
1464                                System.identityHashCode(mHandler));
1465                    }
1466                    break;
1467                case INIT_COPY: {
1468                    HandlerParams params = (HandlerParams) msg.obj;
1469                    int idx = mPendingInstalls.size();
1470                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1471                    // If a bind was already initiated we dont really
1472                    // need to do anything. The pending install
1473                    // will be processed later on.
1474                    if (!mBound) {
1475                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1476                                System.identityHashCode(mHandler));
1477                        // If this is the only one pending we might
1478                        // have to bind to the service again.
1479                        if (!connectToService()) {
1480                            Slog.e(TAG, "Failed to bind to media container service");
1481                            params.serviceError();
1482                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1483                                    System.identityHashCode(mHandler));
1484                            if (params.traceMethod != null) {
1485                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1486                                        params.traceCookie);
1487                            }
1488                            return;
1489                        } else {
1490                            // Once we bind to the service, the first
1491                            // pending request will be processed.
1492                            mPendingInstalls.add(idx, params);
1493                        }
1494                    } else {
1495                        mPendingInstalls.add(idx, params);
1496                        // Already bound to the service. Just make
1497                        // sure we trigger off processing the first request.
1498                        if (idx == 0) {
1499                            mHandler.sendEmptyMessage(MCS_BOUND);
1500                        }
1501                    }
1502                    break;
1503                }
1504                case MCS_BOUND: {
1505                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1506                    if (msg.obj != null) {
1507                        mContainerService = (IMediaContainerService) msg.obj;
1508                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1509                                System.identityHashCode(mHandler));
1510                    }
1511                    if (mContainerService == null) {
1512                        if (!mBound) {
1513                            // Something seriously wrong since we are not bound and we are not
1514                            // waiting for connection. Bail out.
1515                            Slog.e(TAG, "Cannot bind to media container service");
1516                            for (HandlerParams params : mPendingInstalls) {
1517                                // Indicate service bind error
1518                                params.serviceError();
1519                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1520                                        System.identityHashCode(params));
1521                                if (params.traceMethod != null) {
1522                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1523                                            params.traceMethod, params.traceCookie);
1524                                }
1525                                return;
1526                            }
1527                            mPendingInstalls.clear();
1528                        } else {
1529                            Slog.w(TAG, "Waiting to connect to media container service");
1530                        }
1531                    } else if (mPendingInstalls.size() > 0) {
1532                        HandlerParams params = mPendingInstalls.get(0);
1533                        if (params != null) {
1534                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1535                                    System.identityHashCode(params));
1536                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1537                            if (params.startCopy()) {
1538                                // We are done...  look for more work or to
1539                                // go idle.
1540                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1541                                        "Checking for more work or unbind...");
1542                                // Delete pending install
1543                                if (mPendingInstalls.size() > 0) {
1544                                    mPendingInstalls.remove(0);
1545                                }
1546                                if (mPendingInstalls.size() == 0) {
1547                                    if (mBound) {
1548                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1549                                                "Posting delayed MCS_UNBIND");
1550                                        removeMessages(MCS_UNBIND);
1551                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1552                                        // Unbind after a little delay, to avoid
1553                                        // continual thrashing.
1554                                        sendMessageDelayed(ubmsg, 10000);
1555                                    }
1556                                } else {
1557                                    // There are more pending requests in queue.
1558                                    // Just post MCS_BOUND message to trigger processing
1559                                    // of next pending install.
1560                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1561                                            "Posting MCS_BOUND for next work");
1562                                    mHandler.sendEmptyMessage(MCS_BOUND);
1563                                }
1564                            }
1565                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1566                        }
1567                    } else {
1568                        // Should never happen ideally.
1569                        Slog.w(TAG, "Empty queue");
1570                    }
1571                    break;
1572                }
1573                case MCS_RECONNECT: {
1574                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1575                    if (mPendingInstalls.size() > 0) {
1576                        if (mBound) {
1577                            disconnectService();
1578                        }
1579                        if (!connectToService()) {
1580                            Slog.e(TAG, "Failed to bind to media container service");
1581                            for (HandlerParams params : mPendingInstalls) {
1582                                // Indicate service bind error
1583                                params.serviceError();
1584                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1585                                        System.identityHashCode(params));
1586                            }
1587                            mPendingInstalls.clear();
1588                        }
1589                    }
1590                    break;
1591                }
1592                case MCS_UNBIND: {
1593                    // If there is no actual work left, then time to unbind.
1594                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1595
1596                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1597                        if (mBound) {
1598                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1599
1600                            disconnectService();
1601                        }
1602                    } else if (mPendingInstalls.size() > 0) {
1603                        // There are more pending requests in queue.
1604                        // Just post MCS_BOUND message to trigger processing
1605                        // of next pending install.
1606                        mHandler.sendEmptyMessage(MCS_BOUND);
1607                    }
1608
1609                    break;
1610                }
1611                case MCS_GIVE_UP: {
1612                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1613                    HandlerParams params = mPendingInstalls.remove(0);
1614                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1615                            System.identityHashCode(params));
1616                    break;
1617                }
1618                case SEND_PENDING_BROADCAST: {
1619                    String packages[];
1620                    ArrayList<String> components[];
1621                    int size = 0;
1622                    int uids[];
1623                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1624                    synchronized (mPackages) {
1625                        if (mPendingBroadcasts == null) {
1626                            return;
1627                        }
1628                        size = mPendingBroadcasts.size();
1629                        if (size <= 0) {
1630                            // Nothing to be done. Just return
1631                            return;
1632                        }
1633                        packages = new String[size];
1634                        components = new ArrayList[size];
1635                        uids = new int[size];
1636                        int i = 0;  // filling out the above arrays
1637
1638                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1639                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1640                            Iterator<Map.Entry<String, ArrayList<String>>> it
1641                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1642                                            .entrySet().iterator();
1643                            while (it.hasNext() && i < size) {
1644                                Map.Entry<String, ArrayList<String>> ent = it.next();
1645                                packages[i] = ent.getKey();
1646                                components[i] = ent.getValue();
1647                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1648                                uids[i] = (ps != null)
1649                                        ? UserHandle.getUid(packageUserId, ps.appId)
1650                                        : -1;
1651                                i++;
1652                            }
1653                        }
1654                        size = i;
1655                        mPendingBroadcasts.clear();
1656                    }
1657                    // Send broadcasts
1658                    for (int i = 0; i < size; i++) {
1659                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1660                    }
1661                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1662                    break;
1663                }
1664                case START_CLEANING_PACKAGE: {
1665                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1666                    final String packageName = (String)msg.obj;
1667                    final int userId = msg.arg1;
1668                    final boolean andCode = msg.arg2 != 0;
1669                    synchronized (mPackages) {
1670                        if (userId == UserHandle.USER_ALL) {
1671                            int[] users = sUserManager.getUserIds();
1672                            for (int user : users) {
1673                                mSettings.addPackageToCleanLPw(
1674                                        new PackageCleanItem(user, packageName, andCode));
1675                            }
1676                        } else {
1677                            mSettings.addPackageToCleanLPw(
1678                                    new PackageCleanItem(userId, packageName, andCode));
1679                        }
1680                    }
1681                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1682                    startCleaningPackages();
1683                } break;
1684                case POST_INSTALL: {
1685                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1686
1687                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1688                    final boolean didRestore = (msg.arg2 != 0);
1689                    mRunningInstalls.delete(msg.arg1);
1690
1691                    if (data != null) {
1692                        InstallArgs args = data.args;
1693                        PackageInstalledInfo parentRes = data.res;
1694
1695                        final boolean grantPermissions = (args.installFlags
1696                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1697                        final boolean killApp = (args.installFlags
1698                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1699                        final boolean virtualPreload = ((args.installFlags
1700                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1701                        final String[] grantedPermissions = args.installGrantPermissions;
1702
1703                        // Handle the parent package
1704                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1705                                virtualPreload, grantedPermissions, didRestore,
1706                                args.installerPackageName, args.observer);
1707
1708                        // Handle the child packages
1709                        final int childCount = (parentRes.addedChildPackages != null)
1710                                ? parentRes.addedChildPackages.size() : 0;
1711                        for (int i = 0; i < childCount; i++) {
1712                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1713                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1714                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1715                                    args.installerPackageName, args.observer);
1716                        }
1717
1718                        // Log tracing if needed
1719                        if (args.traceMethod != null) {
1720                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1721                                    args.traceCookie);
1722                        }
1723                    } else {
1724                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1725                    }
1726
1727                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1728                } break;
1729                case WRITE_SETTINGS: {
1730                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1731                    synchronized (mPackages) {
1732                        removeMessages(WRITE_SETTINGS);
1733                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1734                        mSettings.writeLPr();
1735                        mDirtyUsers.clear();
1736                    }
1737                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1738                } break;
1739                case WRITE_PACKAGE_RESTRICTIONS: {
1740                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1741                    synchronized (mPackages) {
1742                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1743                        for (int userId : mDirtyUsers) {
1744                            mSettings.writePackageRestrictionsLPr(userId);
1745                        }
1746                        mDirtyUsers.clear();
1747                    }
1748                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1749                } break;
1750                case WRITE_PACKAGE_LIST: {
1751                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1752                    synchronized (mPackages) {
1753                        removeMessages(WRITE_PACKAGE_LIST);
1754                        mSettings.writePackageListLPr(msg.arg1);
1755                    }
1756                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1757                } break;
1758                case CHECK_PENDING_VERIFICATION: {
1759                    final int verificationId = msg.arg1;
1760                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1761
1762                    if ((state != null) && !state.timeoutExtended()) {
1763                        final InstallArgs args = state.getInstallArgs();
1764                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1765
1766                        Slog.i(TAG, "Verification timed out for " + originUri);
1767                        mPendingVerification.remove(verificationId);
1768
1769                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1770
1771                        final UserHandle user = args.getUser();
1772                        if (getDefaultVerificationResponse(user)
1773                                == PackageManager.VERIFICATION_ALLOW) {
1774                            Slog.i(TAG, "Continuing with installation of " + originUri);
1775                            state.setVerifierResponse(Binder.getCallingUid(),
1776                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1777                            broadcastPackageVerified(verificationId, originUri,
1778                                    PackageManager.VERIFICATION_ALLOW, user);
1779                            try {
1780                                ret = args.copyApk(mContainerService, true);
1781                            } catch (RemoteException e) {
1782                                Slog.e(TAG, "Could not contact the ContainerService");
1783                            }
1784                        } else {
1785                            broadcastPackageVerified(verificationId, originUri,
1786                                    PackageManager.VERIFICATION_REJECT, user);
1787                        }
1788
1789                        Trace.asyncTraceEnd(
1790                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1791
1792                        processPendingInstall(args, ret);
1793                        mHandler.sendEmptyMessage(MCS_UNBIND);
1794                    }
1795                    break;
1796                }
1797                case PACKAGE_VERIFIED: {
1798                    final int verificationId = msg.arg1;
1799
1800                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1801                    if (state == null) {
1802                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1803                        break;
1804                    }
1805
1806                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1807
1808                    state.setVerifierResponse(response.callerUid, response.code);
1809
1810                    if (state.isVerificationComplete()) {
1811                        mPendingVerification.remove(verificationId);
1812
1813                        final InstallArgs args = state.getInstallArgs();
1814                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1815
1816                        int ret;
1817                        if (state.isInstallAllowed()) {
1818                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1819                            broadcastPackageVerified(verificationId, originUri,
1820                                    response.code, state.getInstallArgs().getUser());
1821                            try {
1822                                ret = args.copyApk(mContainerService, true);
1823                            } catch (RemoteException e) {
1824                                Slog.e(TAG, "Could not contact the ContainerService");
1825                            }
1826                        } else {
1827                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1828                        }
1829
1830                        Trace.asyncTraceEnd(
1831                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1832
1833                        processPendingInstall(args, ret);
1834                        mHandler.sendEmptyMessage(MCS_UNBIND);
1835                    }
1836
1837                    break;
1838                }
1839                case START_INTENT_FILTER_VERIFICATIONS: {
1840                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1841                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1842                            params.replacing, params.pkg);
1843                    break;
1844                }
1845                case INTENT_FILTER_VERIFIED: {
1846                    final int verificationId = msg.arg1;
1847
1848                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1849                            verificationId);
1850                    if (state == null) {
1851                        Slog.w(TAG, "Invalid IntentFilter verification token "
1852                                + verificationId + " received");
1853                        break;
1854                    }
1855
1856                    final int userId = state.getUserId();
1857
1858                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1859                            "Processing IntentFilter verification with token:"
1860                            + verificationId + " and userId:" + userId);
1861
1862                    final IntentFilterVerificationResponse response =
1863                            (IntentFilterVerificationResponse) msg.obj;
1864
1865                    state.setVerifierResponse(response.callerUid, response.code);
1866
1867                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1868                            "IntentFilter verification with token:" + verificationId
1869                            + " and userId:" + userId
1870                            + " is settings verifier response with response code:"
1871                            + response.code);
1872
1873                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1874                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1875                                + response.getFailedDomainsString());
1876                    }
1877
1878                    if (state.isVerificationComplete()) {
1879                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1880                    } else {
1881                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1882                                "IntentFilter verification with token:" + verificationId
1883                                + " was not said to be complete");
1884                    }
1885
1886                    break;
1887                }
1888                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1889                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1890                            mInstantAppResolverConnection,
1891                            (InstantAppRequest) msg.obj,
1892                            mInstantAppInstallerActivity,
1893                            mHandler);
1894                }
1895            }
1896        }
1897    }
1898
1899    private PermissionCallback mPermissionCallback = new PermissionCallback() {
1900        @Override
1901        public void onGidsChanged(int appId, int userId) {
1902            mHandler.post(new Runnable() {
1903                @Override
1904                public void run() {
1905                    killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
1906                }
1907            });
1908        }
1909        @Override
1910        public void onPermissionGranted(int uid, int userId) {
1911            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1912
1913            // Not critical; if this is lost, the application has to request again.
1914            synchronized (mPackages) {
1915                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1916            }
1917        }
1918        @Override
1919        public void onInstallPermissionGranted() {
1920            synchronized (mPackages) {
1921                scheduleWriteSettingsLocked();
1922            }
1923        }
1924        @Override
1925        public void onPermissionRevoked(int uid, int userId) {
1926            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1927
1928            synchronized (mPackages) {
1929                // Critical; after this call the application should never have the permission
1930                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
1931            }
1932
1933            final int appId = UserHandle.getAppId(uid);
1934            killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
1935        }
1936        @Override
1937        public void onInstallPermissionRevoked() {
1938            synchronized (mPackages) {
1939                scheduleWriteSettingsLocked();
1940            }
1941        }
1942        @Override
1943        public void onPermissionUpdated(int[] updatedUserIds, boolean sync) {
1944            synchronized (mPackages) {
1945                for (int userId : updatedUserIds) {
1946                    mSettings.writeRuntimePermissionsForUserLPr(userId, sync);
1947                }
1948            }
1949        }
1950        @Override
1951        public void onInstallPermissionUpdated() {
1952            synchronized (mPackages) {
1953                scheduleWriteSettingsLocked();
1954            }
1955        }
1956        @Override
1957        public void onPermissionRemoved() {
1958            synchronized (mPackages) {
1959                mSettings.writeLPr();
1960            }
1961        }
1962    };
1963
1964    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1965            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1966            boolean launchedForRestore, String installerPackage,
1967            IPackageInstallObserver2 installObserver) {
1968        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1969            // Send the removed broadcasts
1970            if (res.removedInfo != null) {
1971                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1972            }
1973
1974            // Now that we successfully installed the package, grant runtime
1975            // permissions if requested before broadcasting the install. Also
1976            // for legacy apps in permission review mode we clear the permission
1977            // review flag which is used to emulate runtime permissions for
1978            // legacy apps.
1979            if (grantPermissions) {
1980                final int callingUid = Binder.getCallingUid();
1981                mPermissionManager.grantRequestedRuntimePermissions(
1982                        res.pkg, res.newUsers, grantedPermissions, callingUid,
1983                        mPermissionCallback);
1984            }
1985
1986            final boolean update = res.removedInfo != null
1987                    && res.removedInfo.removedPackage != null;
1988            final String installerPackageName =
1989                    res.installerPackageName != null
1990                            ? res.installerPackageName
1991                            : res.removedInfo != null
1992                                    ? res.removedInfo.installerPackageName
1993                                    : null;
1994
1995            // If this is the first time we have child packages for a disabled privileged
1996            // app that had no children, we grant requested runtime permissions to the new
1997            // children if the parent on the system image had them already granted.
1998            if (res.pkg.parentPackage != null) {
1999                final int callingUid = Binder.getCallingUid();
2000                mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage(
2001                        res.pkg, callingUid, mPermissionCallback);
2002            }
2003
2004            synchronized (mPackages) {
2005                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
2006            }
2007
2008            final String packageName = res.pkg.applicationInfo.packageName;
2009
2010            // Determine the set of users who are adding this package for
2011            // the first time vs. those who are seeing an update.
2012            int[] firstUserIds = EMPTY_INT_ARRAY;
2013            int[] firstInstantUserIds = EMPTY_INT_ARRAY;
2014            int[] updateUserIds = EMPTY_INT_ARRAY;
2015            int[] instantUserIds = EMPTY_INT_ARRAY;
2016            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
2017            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
2018            for (int newUser : res.newUsers) {
2019                final boolean isInstantApp = ps.getInstantApp(newUser);
2020                if (allNewUsers) {
2021                    if (isInstantApp) {
2022                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2023                    } else {
2024                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2025                    }
2026                    continue;
2027                }
2028                boolean isNew = true;
2029                for (int origUser : res.origUsers) {
2030                    if (origUser == newUser) {
2031                        isNew = false;
2032                        break;
2033                    }
2034                }
2035                if (isNew) {
2036                    if (isInstantApp) {
2037                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2038                    } else {
2039                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2040                    }
2041                } else {
2042                    if (isInstantApp) {
2043                        instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser);
2044                    } else {
2045                        updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser);
2046                    }
2047                }
2048            }
2049
2050            // Send installed broadcasts if the package is not a static shared lib.
2051            if (res.pkg.staticSharedLibName == null) {
2052                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
2053
2054                // Send added for users that see the package for the first time
2055                // sendPackageAddedForNewUsers also deals with system apps
2056                int appId = UserHandle.getAppId(res.uid);
2057                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
2058                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
2059                        virtualPreload /*startReceiver*/, appId, firstUserIds, firstInstantUserIds);
2060
2061                // Send added for users that don't see the package for the first time
2062                Bundle extras = new Bundle(1);
2063                extras.putInt(Intent.EXTRA_UID, res.uid);
2064                if (update) {
2065                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2066                }
2067                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2068                        extras, 0 /*flags*/,
2069                        null /*targetPackage*/, null /*finishedReceiver*/,
2070                        updateUserIds, instantUserIds);
2071                if (installerPackageName != null) {
2072                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2073                            extras, 0 /*flags*/,
2074                            installerPackageName, null /*finishedReceiver*/,
2075                            updateUserIds, instantUserIds);
2076                }
2077
2078                // Send replaced for users that don't see the package for the first time
2079                if (update) {
2080                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2081                            packageName, extras, 0 /*flags*/,
2082                            null /*targetPackage*/, null /*finishedReceiver*/,
2083                            updateUserIds, instantUserIds);
2084                    if (installerPackageName != null) {
2085                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2086                                extras, 0 /*flags*/,
2087                                installerPackageName, null /*finishedReceiver*/,
2088                                updateUserIds, instantUserIds);
2089                    }
2090                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2091                            null /*package*/, null /*extras*/, 0 /*flags*/,
2092                            packageName /*targetPackage*/,
2093                            null /*finishedReceiver*/, updateUserIds, instantUserIds);
2094                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2095                    // First-install and we did a restore, so we're responsible for the
2096                    // first-launch broadcast.
2097                    if (DEBUG_BACKUP) {
2098                        Slog.i(TAG, "Post-restore of " + packageName
2099                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds));
2100                    }
2101                    sendFirstLaunchBroadcast(packageName, installerPackage,
2102                            firstUserIds, firstInstantUserIds);
2103                }
2104
2105                // Send broadcast package appeared if forward locked/external for all users
2106                // treat asec-hosted packages like removable media on upgrade
2107                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2108                    if (DEBUG_INSTALL) {
2109                        Slog.i(TAG, "upgrading pkg " + res.pkg
2110                                + " is ASEC-hosted -> AVAILABLE");
2111                    }
2112                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2113                    ArrayList<String> pkgList = new ArrayList<>(1);
2114                    pkgList.add(packageName);
2115                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2116                }
2117            }
2118
2119            // Work that needs to happen on first install within each user
2120            if (firstUserIds != null && firstUserIds.length > 0) {
2121                synchronized (mPackages) {
2122                    for (int userId : firstUserIds) {
2123                        // If this app is a browser and it's newly-installed for some
2124                        // users, clear any default-browser state in those users. The
2125                        // app's nature doesn't depend on the user, so we can just check
2126                        // its browser nature in any user and generalize.
2127                        if (packageIsBrowser(packageName, userId)) {
2128                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2129                        }
2130
2131                        // We may also need to apply pending (restored) runtime
2132                        // permission grants within these users.
2133                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2134                    }
2135                }
2136            }
2137
2138            if (allNewUsers && !update) {
2139                notifyPackageAdded(packageName);
2140            }
2141
2142            // Log current value of "unknown sources" setting
2143            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2144                    getUnknownSourcesSettings());
2145
2146            // Remove the replaced package's older resources safely now
2147            // We delete after a gc for applications  on sdcard.
2148            if (res.removedInfo != null && res.removedInfo.args != null) {
2149                Runtime.getRuntime().gc();
2150                synchronized (mInstallLock) {
2151                    res.removedInfo.args.doPostDeleteLI(true);
2152                }
2153            } else {
2154                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2155                // and not block here.
2156                VMRuntime.getRuntime().requestConcurrentGC();
2157            }
2158
2159            // Notify DexManager that the package was installed for new users.
2160            // The updated users should already be indexed and the package code paths
2161            // should not change.
2162            // Don't notify the manager for ephemeral apps as they are not expected to
2163            // survive long enough to benefit of background optimizations.
2164            for (int userId : firstUserIds) {
2165                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2166                // There's a race currently where some install events may interleave with an uninstall.
2167                // This can lead to package info being null (b/36642664).
2168                if (info != null) {
2169                    mDexManager.notifyPackageInstalled(info, userId);
2170                }
2171            }
2172        }
2173
2174        // If someone is watching installs - notify them
2175        if (installObserver != null) {
2176            try {
2177                Bundle extras = extrasForInstallResult(res);
2178                installObserver.onPackageInstalled(res.name, res.returnCode,
2179                        res.returnMsg, extras);
2180            } catch (RemoteException e) {
2181                Slog.i(TAG, "Observer no longer exists.");
2182            }
2183        }
2184    }
2185
2186    private StorageEventListener mStorageListener = new StorageEventListener() {
2187        @Override
2188        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2189            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2190                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2191                    final String volumeUuid = vol.getFsUuid();
2192
2193                    // Clean up any users or apps that were removed or recreated
2194                    // while this volume was missing
2195                    sUserManager.reconcileUsers(volumeUuid);
2196                    reconcileApps(volumeUuid);
2197
2198                    // Clean up any install sessions that expired or were
2199                    // cancelled while this volume was missing
2200                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2201
2202                    loadPrivatePackages(vol);
2203
2204                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2205                    unloadPrivatePackages(vol);
2206                }
2207            }
2208        }
2209
2210        @Override
2211        public void onVolumeForgotten(String fsUuid) {
2212            if (TextUtils.isEmpty(fsUuid)) {
2213                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2214                return;
2215            }
2216
2217            // Remove any apps installed on the forgotten volume
2218            synchronized (mPackages) {
2219                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2220                for (PackageSetting ps : packages) {
2221                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2222                    deletePackageVersioned(new VersionedPackage(ps.name,
2223                            PackageManager.VERSION_CODE_HIGHEST),
2224                            new LegacyPackageDeleteObserver(null).getBinder(),
2225                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2226                    // Try very hard to release any references to this package
2227                    // so we don't risk the system server being killed due to
2228                    // open FDs
2229                    AttributeCache.instance().removePackage(ps.name);
2230                }
2231
2232                mSettings.onVolumeForgotten(fsUuid);
2233                mSettings.writeLPr();
2234            }
2235        }
2236    };
2237
2238    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2239        Bundle extras = null;
2240        switch (res.returnCode) {
2241            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2242                extras = new Bundle();
2243                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2244                        res.origPermission);
2245                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2246                        res.origPackage);
2247                break;
2248            }
2249            case PackageManager.INSTALL_SUCCEEDED: {
2250                extras = new Bundle();
2251                extras.putBoolean(Intent.EXTRA_REPLACING,
2252                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2253                break;
2254            }
2255        }
2256        return extras;
2257    }
2258
2259    void scheduleWriteSettingsLocked() {
2260        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2261            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2262        }
2263    }
2264
2265    void scheduleWritePackageListLocked(int userId) {
2266        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2267            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2268            msg.arg1 = userId;
2269            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2270        }
2271    }
2272
2273    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2274        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2275        scheduleWritePackageRestrictionsLocked(userId);
2276    }
2277
2278    void scheduleWritePackageRestrictionsLocked(int userId) {
2279        final int[] userIds = (userId == UserHandle.USER_ALL)
2280                ? sUserManager.getUserIds() : new int[]{userId};
2281        for (int nextUserId : userIds) {
2282            if (!sUserManager.exists(nextUserId)) return;
2283            mDirtyUsers.add(nextUserId);
2284            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2285                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2286            }
2287        }
2288    }
2289
2290    public static PackageManagerService main(Context context, Installer installer,
2291            boolean factoryTest, boolean onlyCore) {
2292        // Self-check for initial settings.
2293        PackageManagerServiceCompilerMapping.checkProperties();
2294
2295        PackageManagerService m = new PackageManagerService(context, installer,
2296                factoryTest, onlyCore);
2297        m.enableSystemUserPackages();
2298        ServiceManager.addService("package", m);
2299        final PackageManagerNative pmn = m.new PackageManagerNative();
2300        ServiceManager.addService("package_native", pmn);
2301        return m;
2302    }
2303
2304    private void enableSystemUserPackages() {
2305        if (!UserManager.isSplitSystemUser()) {
2306            return;
2307        }
2308        // For system user, enable apps based on the following conditions:
2309        // - app is whitelisted or belong to one of these groups:
2310        //   -- system app which has no launcher icons
2311        //   -- system app which has INTERACT_ACROSS_USERS permission
2312        //   -- system IME app
2313        // - app is not in the blacklist
2314        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2315        Set<String> enableApps = new ArraySet<>();
2316        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2317                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2318                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2319        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2320        enableApps.addAll(wlApps);
2321        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2322                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2323        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2324        enableApps.removeAll(blApps);
2325        Log.i(TAG, "Applications installed for system user: " + enableApps);
2326        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2327                UserHandle.SYSTEM);
2328        final int allAppsSize = allAps.size();
2329        synchronized (mPackages) {
2330            for (int i = 0; i < allAppsSize; i++) {
2331                String pName = allAps.get(i);
2332                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2333                // Should not happen, but we shouldn't be failing if it does
2334                if (pkgSetting == null) {
2335                    continue;
2336                }
2337                boolean install = enableApps.contains(pName);
2338                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2339                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2340                            + " for system user");
2341                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2342                }
2343            }
2344            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2345        }
2346    }
2347
2348    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2349        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2350                Context.DISPLAY_SERVICE);
2351        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2352    }
2353
2354    /**
2355     * Requests that files preopted on a secondary system partition be copied to the data partition
2356     * if possible.  Note that the actual copying of the files is accomplished by init for security
2357     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2358     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2359     */
2360    private static void requestCopyPreoptedFiles() {
2361        final int WAIT_TIME_MS = 100;
2362        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2363        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2364            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2365            // We will wait for up to 100 seconds.
2366            final long timeStart = SystemClock.uptimeMillis();
2367            final long timeEnd = timeStart + 100 * 1000;
2368            long timeNow = timeStart;
2369            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2370                try {
2371                    Thread.sleep(WAIT_TIME_MS);
2372                } catch (InterruptedException e) {
2373                    // Do nothing
2374                }
2375                timeNow = SystemClock.uptimeMillis();
2376                if (timeNow > timeEnd) {
2377                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2378                    Slog.wtf(TAG, "cppreopt did not finish!");
2379                    break;
2380                }
2381            }
2382
2383            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2384        }
2385    }
2386
2387    public PackageManagerService(Context context, Installer installer,
2388            boolean factoryTest, boolean onlyCore) {
2389        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2390        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2391        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2392                SystemClock.uptimeMillis());
2393
2394        if (mSdkVersion <= 0) {
2395            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2396        }
2397
2398        mContext = context;
2399
2400        mFactoryTest = factoryTest;
2401        mOnlyCore = onlyCore;
2402        mMetrics = new DisplayMetrics();
2403        mInstaller = installer;
2404
2405        // Create sub-components that provide services / data. Order here is important.
2406        synchronized (mInstallLock) {
2407        synchronized (mPackages) {
2408            // Expose private service for system components to use.
2409            LocalServices.addService(
2410                    PackageManagerInternal.class, new PackageManagerInternalImpl());
2411            sUserManager = new UserManagerService(context, this,
2412                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2413            mPermissionManager = PermissionManagerService.create(context,
2414                    new DefaultPermissionGrantedCallback() {
2415                        @Override
2416                        public void onDefaultRuntimePermissionsGranted(int userId) {
2417                            synchronized(mPackages) {
2418                                mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);
2419                            }
2420                        }
2421                    }, mPackages /*externalLock*/);
2422            mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy();
2423            mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages);
2424        }
2425        }
2426        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2427                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2428        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2429                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2430        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2431                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2432        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2433                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2434        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2435                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2436        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2437                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2438        mSettings.addSharedUserLPw("android.uid.se", SE_UID,
2439                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2440
2441        String separateProcesses = SystemProperties.get("debug.separate_processes");
2442        if (separateProcesses != null && separateProcesses.length() > 0) {
2443            if ("*".equals(separateProcesses)) {
2444                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2445                mSeparateProcesses = null;
2446                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2447            } else {
2448                mDefParseFlags = 0;
2449                mSeparateProcesses = separateProcesses.split(",");
2450                Slog.w(TAG, "Running with debug.separate_processes: "
2451                        + separateProcesses);
2452            }
2453        } else {
2454            mDefParseFlags = 0;
2455            mSeparateProcesses = null;
2456        }
2457
2458        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2459                "*dexopt*");
2460        DexManager.Listener dexManagerListener = DexLogger.getListener(this,
2461                installer, mInstallLock);
2462        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock,
2463                dexManagerListener);
2464        mArtManagerService = new ArtManagerService(this, installer, mInstallLock);
2465        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2466
2467        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2468                FgThread.get().getLooper());
2469
2470        getDefaultDisplayMetrics(context, mMetrics);
2471
2472        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2473        SystemConfig systemConfig = SystemConfig.getInstance();
2474        mAvailableFeatures = systemConfig.getAvailableFeatures();
2475        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2476
2477        mProtectedPackages = new ProtectedPackages(mContext);
2478
2479        synchronized (mInstallLock) {
2480        // writer
2481        synchronized (mPackages) {
2482            mHandlerThread = new ServiceThread(TAG,
2483                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2484            mHandlerThread.start();
2485            mHandler = new PackageHandler(mHandlerThread.getLooper());
2486            mProcessLoggingHandler = new ProcessLoggingHandler();
2487            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2488            mInstantAppRegistry = new InstantAppRegistry(this);
2489
2490            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2491            final int builtInLibCount = libConfig.size();
2492            for (int i = 0; i < builtInLibCount; i++) {
2493                String name = libConfig.keyAt(i);
2494                String path = libConfig.valueAt(i);
2495                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2496                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2497            }
2498
2499            SELinuxMMAC.readInstallPolicy();
2500
2501            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2502            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2503            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2504
2505            // Clean up orphaned packages for which the code path doesn't exist
2506            // and they are an update to a system app - caused by bug/32321269
2507            final int packageSettingCount = mSettings.mPackages.size();
2508            for (int i = packageSettingCount - 1; i >= 0; i--) {
2509                PackageSetting ps = mSettings.mPackages.valueAt(i);
2510                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2511                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2512                    mSettings.mPackages.removeAt(i);
2513                    mSettings.enableSystemPackageLPw(ps.name);
2514                }
2515            }
2516
2517            if (mFirstBoot) {
2518                requestCopyPreoptedFiles();
2519            }
2520
2521            String customResolverActivity = Resources.getSystem().getString(
2522                    R.string.config_customResolverActivity);
2523            if (TextUtils.isEmpty(customResolverActivity)) {
2524                customResolverActivity = null;
2525            } else {
2526                mCustomResolverComponentName = ComponentName.unflattenFromString(
2527                        customResolverActivity);
2528            }
2529
2530            long startTime = SystemClock.uptimeMillis();
2531
2532            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2533                    startTime);
2534
2535            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2536            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2537
2538            if (bootClassPath == null) {
2539                Slog.w(TAG, "No BOOTCLASSPATH found!");
2540            }
2541
2542            if (systemServerClassPath == null) {
2543                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2544            }
2545
2546            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2547
2548            final VersionInfo ver = mSettings.getInternalVersion();
2549            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2550            if (mIsUpgrade) {
2551                logCriticalInfo(Log.INFO,
2552                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2553            }
2554
2555            // when upgrading from pre-M, promote system app permissions from install to runtime
2556            mPromoteSystemApps =
2557                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2558
2559            // When upgrading from pre-N, we need to handle package extraction like first boot,
2560            // as there is no profiling data available.
2561            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2562
2563            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2564
2565            // save off the names of pre-existing system packages prior to scanning; we don't
2566            // want to automatically grant runtime permissions for new system apps
2567            if (mPromoteSystemApps) {
2568                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2569                while (pkgSettingIter.hasNext()) {
2570                    PackageSetting ps = pkgSettingIter.next();
2571                    if (isSystemApp(ps)) {
2572                        mExistingSystemPackages.add(ps.name);
2573                    }
2574                }
2575            }
2576
2577            mCacheDir = preparePackageParserCache(mIsUpgrade);
2578
2579            // Set flag to monitor and not change apk file paths when
2580            // scanning install directories.
2581            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2582
2583            if (mIsUpgrade || mFirstBoot) {
2584                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2585            }
2586
2587            // Collect vendor/product overlay packages. (Do this before scanning any apps.)
2588            // For security and version matching reason, only consider
2589            // overlay packages if they reside in the right directory.
2590            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR),
2591                    mDefParseFlags
2592                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2593                    scanFlags
2594                    | SCAN_AS_SYSTEM
2595                    | SCAN_AS_VENDOR,
2596                    0);
2597            scanDirTracedLI(new File(PRODUCT_OVERLAY_DIR),
2598                    mDefParseFlags
2599                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2600                    scanFlags
2601                    | SCAN_AS_SYSTEM
2602                    | SCAN_AS_PRODUCT,
2603                    0);
2604
2605            mParallelPackageParserCallback.findStaticOverlayPackages();
2606
2607            // Find base frameworks (resource packages without code).
2608            scanDirTracedLI(frameworkDir,
2609                    mDefParseFlags
2610                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2611                    scanFlags
2612                    | SCAN_NO_DEX
2613                    | SCAN_AS_SYSTEM
2614                    | SCAN_AS_PRIVILEGED,
2615                    0);
2616
2617            // Collect privileged system packages.
2618            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2619            scanDirTracedLI(privilegedAppDir,
2620                    mDefParseFlags
2621                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2622                    scanFlags
2623                    | SCAN_AS_SYSTEM
2624                    | SCAN_AS_PRIVILEGED,
2625                    0);
2626
2627            // Collect ordinary system packages.
2628            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2629            scanDirTracedLI(systemAppDir,
2630                    mDefParseFlags
2631                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2632                    scanFlags
2633                    | SCAN_AS_SYSTEM,
2634                    0);
2635
2636            // Collect privileged vendor packages.
2637            File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
2638            try {
2639                privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile();
2640            } catch (IOException e) {
2641                // failed to look up canonical path, continue with original one
2642            }
2643            scanDirTracedLI(privilegedVendorAppDir,
2644                    mDefParseFlags
2645                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2646                    scanFlags
2647                    | SCAN_AS_SYSTEM
2648                    | SCAN_AS_VENDOR
2649                    | SCAN_AS_PRIVILEGED,
2650                    0);
2651
2652            // Collect ordinary vendor packages.
2653            File vendorAppDir = new File(Environment.getVendorDirectory(), "app");
2654            try {
2655                vendorAppDir = vendorAppDir.getCanonicalFile();
2656            } catch (IOException e) {
2657                // failed to look up canonical path, continue with original one
2658            }
2659            scanDirTracedLI(vendorAppDir,
2660                    mDefParseFlags
2661                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2662                    scanFlags
2663                    | SCAN_AS_SYSTEM
2664                    | SCAN_AS_VENDOR,
2665                    0);
2666
2667            // Collect privileged odm packages. /odm is another vendor partition
2668            // other than /vendor.
2669            File privilegedOdmAppDir = new File(Environment.getOdmDirectory(),
2670                        "priv-app");
2671            try {
2672                privilegedOdmAppDir = privilegedOdmAppDir.getCanonicalFile();
2673            } catch (IOException e) {
2674                // failed to look up canonical path, continue with original one
2675            }
2676            scanDirTracedLI(privilegedOdmAppDir,
2677                    mDefParseFlags
2678                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2679                    scanFlags
2680                    | SCAN_AS_SYSTEM
2681                    | SCAN_AS_VENDOR
2682                    | SCAN_AS_PRIVILEGED,
2683                    0);
2684
2685            // Collect ordinary odm packages. /odm is another vendor partition
2686            // other than /vendor.
2687            File odmAppDir = new File(Environment.getOdmDirectory(), "app");
2688            try {
2689                odmAppDir = odmAppDir.getCanonicalFile();
2690            } catch (IOException e) {
2691                // failed to look up canonical path, continue with original one
2692            }
2693            scanDirTracedLI(odmAppDir,
2694                    mDefParseFlags
2695                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2696                    scanFlags
2697                    | SCAN_AS_SYSTEM
2698                    | SCAN_AS_VENDOR,
2699                    0);
2700
2701            // Collect all OEM packages.
2702            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2703            scanDirTracedLI(oemAppDir,
2704                    mDefParseFlags
2705                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2706                    scanFlags
2707                    | SCAN_AS_SYSTEM
2708                    | SCAN_AS_OEM,
2709                    0);
2710
2711            // Collected privileged product packages.
2712            File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
2713            try {
2714                privilegedProductAppDir = privilegedProductAppDir.getCanonicalFile();
2715            } catch (IOException e) {
2716                // failed to look up canonical path, continue with original one
2717            }
2718            scanDirTracedLI(privilegedProductAppDir,
2719                    mDefParseFlags
2720                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2721                    scanFlags
2722                    | SCAN_AS_SYSTEM
2723                    | SCAN_AS_PRODUCT
2724                    | SCAN_AS_PRIVILEGED,
2725                    0);
2726
2727            // Collect ordinary product packages.
2728            File productAppDir = new File(Environment.getProductDirectory(), "app");
2729            try {
2730                productAppDir = productAppDir.getCanonicalFile();
2731            } catch (IOException e) {
2732                // failed to look up canonical path, continue with original one
2733            }
2734            scanDirTracedLI(productAppDir,
2735                    mDefParseFlags
2736                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2737                    scanFlags
2738                    | SCAN_AS_SYSTEM
2739                    | SCAN_AS_PRODUCT,
2740                    0);
2741
2742            // Prune any system packages that no longer exist.
2743            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2744            // Stub packages must either be replaced with full versions in the /data
2745            // partition or be disabled.
2746            final List<String> stubSystemApps = new ArrayList<>();
2747            if (!mOnlyCore) {
2748                // do this first before mucking with mPackages for the "expecting better" case
2749                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2750                while (pkgIterator.hasNext()) {
2751                    final PackageParser.Package pkg = pkgIterator.next();
2752                    if (pkg.isStub) {
2753                        stubSystemApps.add(pkg.packageName);
2754                    }
2755                }
2756
2757                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2758                while (psit.hasNext()) {
2759                    PackageSetting ps = psit.next();
2760
2761                    /*
2762                     * If this is not a system app, it can't be a
2763                     * disable system app.
2764                     */
2765                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2766                        continue;
2767                    }
2768
2769                    /*
2770                     * If the package is scanned, it's not erased.
2771                     */
2772                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2773                    if (scannedPkg != null) {
2774                        /*
2775                         * If the system app is both scanned and in the
2776                         * disabled packages list, then it must have been
2777                         * added via OTA. Remove it from the currently
2778                         * scanned package so the previously user-installed
2779                         * application can be scanned.
2780                         */
2781                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2782                            logCriticalInfo(Log.WARN,
2783                                    "Expecting better updated system app for " + ps.name
2784                                    + "; removing system app.  Last known"
2785                                    + " codePath=" + ps.codePathString
2786                                    + ", versionCode=" + ps.versionCode
2787                                    + "; scanned versionCode=" + scannedPkg.getLongVersionCode());
2788                            removePackageLI(scannedPkg, true);
2789                            mExpectingBetter.put(ps.name, ps.codePath);
2790                        }
2791
2792                        continue;
2793                    }
2794
2795                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2796                        psit.remove();
2797                        logCriticalInfo(Log.WARN, "System package " + ps.name
2798                                + " no longer exists; it's data will be wiped");
2799                        // Actual deletion of code and data will be handled by later
2800                        // reconciliation step
2801                    } else {
2802                        // we still have a disabled system package, but, it still might have
2803                        // been removed. check the code path still exists and check there's
2804                        // still a package. the latter can happen if an OTA keeps the same
2805                        // code path, but, changes the package name.
2806                        final PackageSetting disabledPs =
2807                                mSettings.getDisabledSystemPkgLPr(ps.name);
2808                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2809                                || disabledPs.pkg == null) {
2810                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2811                        }
2812                    }
2813                }
2814            }
2815
2816            //delete tmp files
2817            deleteTempPackageFiles();
2818
2819            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2820
2821            // Remove any shared userIDs that have no associated packages
2822            mSettings.pruneSharedUsersLPw();
2823            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2824            final int systemPackagesCount = mPackages.size();
2825            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2826                    + " ms, packageCount: " + systemPackagesCount
2827                    + " , timePerPackage: "
2828                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2829                    + " , cached: " + cachedSystemApps);
2830            if (mIsUpgrade && systemPackagesCount > 0) {
2831                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2832                        ((int) systemScanTime) / systemPackagesCount);
2833            }
2834            if (!mOnlyCore) {
2835                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2836                        SystemClock.uptimeMillis());
2837                scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2838
2839                scanDirTracedLI(sDrmAppPrivateInstallDir, mDefParseFlags
2840                        | PackageParser.PARSE_FORWARD_LOCK,
2841                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2842
2843                // Remove disable package settings for updated system apps that were
2844                // removed via an OTA. If the update is no longer present, remove the
2845                // app completely. Otherwise, revoke their system privileges.
2846                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2847                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2848                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2849                    final String msg;
2850                    if (deletedPkg == null) {
2851                        // should have found an update, but, we didn't; remove everything
2852                        msg = "Updated system package " + deletedAppName
2853                                + " no longer exists; removing its data";
2854                        // Actual deletion of code and data will be handled by later
2855                        // reconciliation step
2856                    } else {
2857                        // found an update; revoke system privileges
2858                        msg = "Updated system package + " + deletedAppName
2859                                + " no longer exists; revoking system privileges";
2860
2861                        // Don't do anything if a stub is removed from the system image. If
2862                        // we were to remove the uncompressed version from the /data partition,
2863                        // this is where it'd be done.
2864
2865                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2866                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2867                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2868                    }
2869                    logCriticalInfo(Log.WARN, msg);
2870                }
2871
2872                /*
2873                 * Make sure all system apps that we expected to appear on
2874                 * the userdata partition actually showed up. If they never
2875                 * appeared, crawl back and revive the system version.
2876                 */
2877                for (int i = 0; i < mExpectingBetter.size(); i++) {
2878                    final String packageName = mExpectingBetter.keyAt(i);
2879                    if (!mPackages.containsKey(packageName)) {
2880                        final File scanFile = mExpectingBetter.valueAt(i);
2881
2882                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2883                                + " but never showed up; reverting to system");
2884
2885                        final @ParseFlags int reparseFlags;
2886                        final @ScanFlags int rescanFlags;
2887                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2888                            reparseFlags =
2889                                    mDefParseFlags |
2890                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2891                            rescanFlags =
2892                                    scanFlags
2893                                    | SCAN_AS_SYSTEM
2894                                    | SCAN_AS_PRIVILEGED;
2895                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2896                            reparseFlags =
2897                                    mDefParseFlags |
2898                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2899                            rescanFlags =
2900                                    scanFlags
2901                                    | SCAN_AS_SYSTEM;
2902                        } else if (FileUtils.contains(privilegedVendorAppDir, scanFile)
2903                                || FileUtils.contains(privilegedOdmAppDir, scanFile)) {
2904                            reparseFlags =
2905                                    mDefParseFlags |
2906                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2907                            rescanFlags =
2908                                    scanFlags
2909                                    | SCAN_AS_SYSTEM
2910                                    | SCAN_AS_VENDOR
2911                                    | SCAN_AS_PRIVILEGED;
2912                        } else if (FileUtils.contains(vendorAppDir, scanFile)
2913                                || FileUtils.contains(odmAppDir, scanFile)) {
2914                            reparseFlags =
2915                                    mDefParseFlags |
2916                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2917                            rescanFlags =
2918                                    scanFlags
2919                                    | SCAN_AS_SYSTEM
2920                                    | SCAN_AS_VENDOR;
2921                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2922                            reparseFlags =
2923                                    mDefParseFlags |
2924                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2925                            rescanFlags =
2926                                    scanFlags
2927                                    | SCAN_AS_SYSTEM
2928                                    | SCAN_AS_OEM;
2929                        } else if (FileUtils.contains(privilegedProductAppDir, scanFile)) {
2930                            reparseFlags =
2931                                    mDefParseFlags |
2932                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2933                            rescanFlags =
2934                                    scanFlags
2935                                    | SCAN_AS_SYSTEM
2936                                    | SCAN_AS_PRODUCT
2937                                    | SCAN_AS_PRIVILEGED;
2938                        } else if (FileUtils.contains(productAppDir, scanFile)) {
2939                            reparseFlags =
2940                                    mDefParseFlags |
2941                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2942                            rescanFlags =
2943                                    scanFlags
2944                                    | SCAN_AS_SYSTEM
2945                                    | SCAN_AS_PRODUCT;
2946                        } else {
2947                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2948                            continue;
2949                        }
2950
2951                        mSettings.enableSystemPackageLPw(packageName);
2952
2953                        try {
2954                            scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null);
2955                        } catch (PackageManagerException e) {
2956                            Slog.e(TAG, "Failed to parse original system package: "
2957                                    + e.getMessage());
2958                        }
2959                    }
2960                }
2961
2962                // Uncompress and install any stubbed system applications.
2963                // This must be done last to ensure all stubs are replaced or disabled.
2964                decompressSystemApplications(stubSystemApps, scanFlags);
2965
2966                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2967                                - cachedSystemApps;
2968
2969                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2970                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2971                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2972                        + " ms, packageCount: " + dataPackagesCount
2973                        + " , timePerPackage: "
2974                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2975                        + " , cached: " + cachedNonSystemApps);
2976                if (mIsUpgrade && dataPackagesCount > 0) {
2977                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2978                            ((int) dataScanTime) / dataPackagesCount);
2979                }
2980            }
2981            mExpectingBetter.clear();
2982
2983            // Resolve the storage manager.
2984            mStorageManagerPackage = getStorageManagerPackageName();
2985
2986            // Resolve protected action filters. Only the setup wizard is allowed to
2987            // have a high priority filter for these actions.
2988            mSetupWizardPackage = getSetupWizardPackageName();
2989            if (mProtectedFilters.size() > 0) {
2990                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2991                    Slog.i(TAG, "No setup wizard;"
2992                        + " All protected intents capped to priority 0");
2993                }
2994                for (ActivityIntentInfo filter : mProtectedFilters) {
2995                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2996                        if (DEBUG_FILTERS) {
2997                            Slog.i(TAG, "Found setup wizard;"
2998                                + " allow priority " + filter.getPriority() + ";"
2999                                + " package: " + filter.activity.info.packageName
3000                                + " activity: " + filter.activity.className
3001                                + " priority: " + filter.getPriority());
3002                        }
3003                        // skip setup wizard; allow it to keep the high priority filter
3004                        continue;
3005                    }
3006                    if (DEBUG_FILTERS) {
3007                        Slog.i(TAG, "Protected action; cap priority to 0;"
3008                                + " package: " + filter.activity.info.packageName
3009                                + " activity: " + filter.activity.className
3010                                + " origPrio: " + filter.getPriority());
3011                    }
3012                    filter.setPriority(0);
3013                }
3014            }
3015
3016            mSystemTextClassifierPackage = getSystemTextClassifierPackageName();
3017
3018            mDeferProtectedFilters = false;
3019            mProtectedFilters.clear();
3020
3021            // Now that we know all of the shared libraries, update all clients to have
3022            // the correct library paths.
3023            updateAllSharedLibrariesLPw(null);
3024
3025            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
3026                // NOTE: We ignore potential failures here during a system scan (like
3027                // the rest of the commands above) because there's precious little we
3028                // can do about it. A settings error is reported, though.
3029                final List<String> changedAbiCodePath =
3030                        adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
3031                if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
3032                    for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
3033                        final String codePathString = changedAbiCodePath.get(i);
3034                        try {
3035                            mInstaller.rmdex(codePathString,
3036                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
3037                        } catch (InstallerException ignored) {
3038                        }
3039                    }
3040                }
3041                // Adjust seInfo to ensure apps which share a sharedUserId are placed in the same
3042                // SELinux domain.
3043                setting.fixSeInfoLocked();
3044            }
3045
3046            // Now that we know all the packages we are keeping,
3047            // read and update their last usage times.
3048            mPackageUsage.read(mPackages);
3049            mCompilerStats.read();
3050
3051            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
3052                    SystemClock.uptimeMillis());
3053            Slog.i(TAG, "Time to scan packages: "
3054                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
3055                    + " seconds");
3056
3057            // If the platform SDK has changed since the last time we booted,
3058            // we need to re-grant app permission to catch any new ones that
3059            // appear.  This is really a hack, and means that apps can in some
3060            // cases get permissions that the user didn't initially explicitly
3061            // allow...  it would be nice to have some better way to handle
3062            // this situation.
3063            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
3064            if (sdkUpdated) {
3065                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
3066                        + mSdkVersion + "; regranting permissions for internal storage");
3067            }
3068            mPermissionManager.updateAllPermissions(
3069                    StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(),
3070                    mPermissionCallback);
3071            ver.sdkVersion = mSdkVersion;
3072
3073            // If this is the first boot or an update from pre-M, and it is a normal
3074            // boot, then we need to initialize the default preferred apps across
3075            // all defined users.
3076            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
3077                for (UserInfo user : sUserManager.getUsers(true)) {
3078                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
3079                    applyFactoryDefaultBrowserLPw(user.id);
3080                    primeDomainVerificationsLPw(user.id);
3081                }
3082            }
3083
3084            // Prepare storage for system user really early during boot,
3085            // since core system apps like SettingsProvider and SystemUI
3086            // can't wait for user to start
3087            final int storageFlags;
3088            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
3089                storageFlags = StorageManager.FLAG_STORAGE_DE;
3090            } else {
3091                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
3092            }
3093            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
3094                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
3095                    true /* onlyCoreApps */);
3096            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
3097                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
3098                        Trace.TRACE_TAG_PACKAGE_MANAGER);
3099                traceLog.traceBegin("AppDataFixup");
3100                try {
3101                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
3102                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
3103                } catch (InstallerException e) {
3104                    Slog.w(TAG, "Trouble fixing GIDs", e);
3105                }
3106                traceLog.traceEnd();
3107
3108                traceLog.traceBegin("AppDataPrepare");
3109                if (deferPackages == null || deferPackages.isEmpty()) {
3110                    return;
3111                }
3112                int count = 0;
3113                for (String pkgName : deferPackages) {
3114                    PackageParser.Package pkg = null;
3115                    synchronized (mPackages) {
3116                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
3117                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
3118                            pkg = ps.pkg;
3119                        }
3120                    }
3121                    if (pkg != null) {
3122                        synchronized (mInstallLock) {
3123                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
3124                                    true /* maybeMigrateAppData */);
3125                        }
3126                        count++;
3127                    }
3128                }
3129                traceLog.traceEnd();
3130                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
3131            }, "prepareAppData");
3132
3133            // If this is first boot after an OTA, and a normal boot, then
3134            // we need to clear code cache directories.
3135            // Note that we do *not* clear the application profiles. These remain valid
3136            // across OTAs and are used to drive profile verification (post OTA) and
3137            // profile compilation (without waiting to collect a fresh set of profiles).
3138            if (mIsUpgrade && !onlyCore) {
3139                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
3140                for (int i = 0; i < mSettings.mPackages.size(); i++) {
3141                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
3142                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
3143                        // No apps are running this early, so no need to freeze
3144                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
3145                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3146                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3147                    }
3148                }
3149                ver.fingerprint = Build.FINGERPRINT;
3150            }
3151
3152            checkDefaultBrowser();
3153
3154            // clear only after permissions and other defaults have been updated
3155            mExistingSystemPackages.clear();
3156            mPromoteSystemApps = false;
3157
3158            // All the changes are done during package scanning.
3159            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3160
3161            // can downgrade to reader
3162            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3163            mSettings.writeLPr();
3164            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3165            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3166                    SystemClock.uptimeMillis());
3167
3168            if (!mOnlyCore) {
3169                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3170                mRequiredInstallerPackage = getRequiredInstallerLPr();
3171                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3172                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3173                if (mIntentFilterVerifierComponent != null) {
3174                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3175                            mIntentFilterVerifierComponent);
3176                } else {
3177                    mIntentFilterVerifier = null;
3178                }
3179                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3180                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3181                        SharedLibraryInfo.VERSION_UNDEFINED);
3182                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3183                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3184                        SharedLibraryInfo.VERSION_UNDEFINED);
3185            } else {
3186                mRequiredVerifierPackage = null;
3187                mRequiredInstallerPackage = null;
3188                mRequiredUninstallerPackage = null;
3189                mIntentFilterVerifierComponent = null;
3190                mIntentFilterVerifier = null;
3191                mServicesSystemSharedLibraryPackageName = null;
3192                mSharedSystemSharedLibraryPackageName = null;
3193            }
3194
3195            mInstallerService = new PackageInstallerService(context, this);
3196            final Pair<ComponentName, String> instantAppResolverComponent =
3197                    getInstantAppResolverLPr();
3198            if (instantAppResolverComponent != null) {
3199                if (DEBUG_INSTANT) {
3200                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3201                }
3202                mInstantAppResolverConnection = new InstantAppResolverConnection(
3203                        mContext, instantAppResolverComponent.first,
3204                        instantAppResolverComponent.second);
3205                mInstantAppResolverSettingsComponent =
3206                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3207            } else {
3208                mInstantAppResolverConnection = null;
3209                mInstantAppResolverSettingsComponent = null;
3210            }
3211            updateInstantAppInstallerLocked(null);
3212
3213            // Read and update the usage of dex files.
3214            // Do this at the end of PM init so that all the packages have their
3215            // data directory reconciled.
3216            // At this point we know the code paths of the packages, so we can validate
3217            // the disk file and build the internal cache.
3218            // The usage file is expected to be small so loading and verifying it
3219            // should take a fairly small time compare to the other activities (e.g. package
3220            // scanning).
3221            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3222            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3223            for (int userId : currentUserIds) {
3224                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3225            }
3226            mDexManager.load(userPackages);
3227            if (mIsUpgrade) {
3228                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3229                        (int) (SystemClock.uptimeMillis() - startTime));
3230            }
3231        } // synchronized (mPackages)
3232        } // synchronized (mInstallLock)
3233
3234        // Now after opening every single application zip, make sure they
3235        // are all flushed.  Not really needed, but keeps things nice and
3236        // tidy.
3237        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3238        Runtime.getRuntime().gc();
3239        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3240
3241        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3242        FallbackCategoryProvider.loadFallbacks();
3243        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3244
3245        // The initial scanning above does many calls into installd while
3246        // holding the mPackages lock, but we're mostly interested in yelling
3247        // once we have a booted system.
3248        mInstaller.setWarnIfHeld(mPackages);
3249
3250        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3251    }
3252
3253    /**
3254     * Uncompress and install stub applications.
3255     * <p>In order to save space on the system partition, some applications are shipped in a
3256     * compressed form. In addition the compressed bits for the full application, the
3257     * system image contains a tiny stub comprised of only the Android manifest.
3258     * <p>During the first boot, attempt to uncompress and install the full application. If
3259     * the application can't be installed for any reason, disable the stub and prevent
3260     * uncompressing the full application during future boots.
3261     * <p>In order to forcefully attempt an installation of a full application, go to app
3262     * settings and enable the application.
3263     */
3264    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3265        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3266            final String pkgName = stubSystemApps.get(i);
3267            // skip if the system package is already disabled
3268            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3269                stubSystemApps.remove(i);
3270                continue;
3271            }
3272            // skip if the package isn't installed (?!); this should never happen
3273            final PackageParser.Package pkg = mPackages.get(pkgName);
3274            if (pkg == null) {
3275                stubSystemApps.remove(i);
3276                continue;
3277            }
3278            // skip if the package has been disabled by the user
3279            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3280            if (ps != null) {
3281                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3282                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3283                    stubSystemApps.remove(i);
3284                    continue;
3285                }
3286            }
3287
3288            if (DEBUG_COMPRESSION) {
3289                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3290            }
3291
3292            // uncompress the binary to its eventual destination on /data
3293            final File scanFile = decompressPackage(pkg);
3294            if (scanFile == null) {
3295                continue;
3296            }
3297
3298            // install the package to replace the stub on /system
3299            try {
3300                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3301                removePackageLI(pkg, true /*chatty*/);
3302                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3303                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3304                        UserHandle.USER_SYSTEM, "android");
3305                stubSystemApps.remove(i);
3306                continue;
3307            } catch (PackageManagerException e) {
3308                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3309            }
3310
3311            // any failed attempt to install the package will be cleaned up later
3312        }
3313
3314        // disable any stub still left; these failed to install the full application
3315        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3316            final String pkgName = stubSystemApps.get(i);
3317            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3318            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3319                    UserHandle.USER_SYSTEM, "android");
3320            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3321        }
3322    }
3323
3324    /**
3325     * Decompresses the given package on the system image onto
3326     * the /data partition.
3327     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3328     */
3329    private File decompressPackage(PackageParser.Package pkg) {
3330        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3331        if (compressedFiles == null || compressedFiles.length == 0) {
3332            if (DEBUG_COMPRESSION) {
3333                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3334            }
3335            return null;
3336        }
3337        final File dstCodePath =
3338                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3339        int ret = PackageManager.INSTALL_SUCCEEDED;
3340        try {
3341            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3342            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3343            for (File srcFile : compressedFiles) {
3344                final String srcFileName = srcFile.getName();
3345                final String dstFileName = srcFileName.substring(
3346                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3347                final File dstFile = new File(dstCodePath, dstFileName);
3348                ret = decompressFile(srcFile, dstFile);
3349                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3350                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3351                            + "; pkg: " + pkg.packageName
3352                            + ", file: " + dstFileName);
3353                    break;
3354                }
3355            }
3356        } catch (ErrnoException e) {
3357            logCriticalInfo(Log.ERROR, "Failed to decompress"
3358                    + "; pkg: " + pkg.packageName
3359                    + ", err: " + e.errno);
3360        }
3361        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3362            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3363            NativeLibraryHelper.Handle handle = null;
3364            try {
3365                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3366                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3367                        null /*abiOverride*/);
3368            } catch (IOException e) {
3369                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3370                        + "; pkg: " + pkg.packageName);
3371                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3372            } finally {
3373                IoUtils.closeQuietly(handle);
3374            }
3375        }
3376        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3377            if (dstCodePath == null || !dstCodePath.exists()) {
3378                return null;
3379            }
3380            removeCodePathLI(dstCodePath);
3381            return null;
3382        }
3383
3384        return dstCodePath;
3385    }
3386
3387    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3388        // we're only interested in updating the installer appliction when 1) it's not
3389        // already set or 2) the modified package is the installer
3390        if (mInstantAppInstallerActivity != null
3391                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3392                        .equals(modifiedPackage)) {
3393            return;
3394        }
3395        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3396    }
3397
3398    private static File preparePackageParserCache(boolean isUpgrade) {
3399        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3400            return null;
3401        }
3402
3403        // Disable package parsing on eng builds to allow for faster incremental development.
3404        if (Build.IS_ENG) {
3405            return null;
3406        }
3407
3408        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3409            Slog.i(TAG, "Disabling package parser cache due to system property.");
3410            return null;
3411        }
3412
3413        // The base directory for the package parser cache lives under /data/system/.
3414        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3415                "package_cache");
3416        if (cacheBaseDir == null) {
3417            return null;
3418        }
3419
3420        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3421        // This also serves to "GC" unused entries when the package cache version changes (which
3422        // can only happen during upgrades).
3423        if (isUpgrade) {
3424            FileUtils.deleteContents(cacheBaseDir);
3425        }
3426
3427
3428        // Return the versioned package cache directory. This is something like
3429        // "/data/system/package_cache/1"
3430        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3431
3432        if (cacheDir == null) {
3433            // Something went wrong. Attempt to delete everything and return.
3434            Slog.wtf(TAG, "Cache directory cannot be created - wiping base dir " + cacheBaseDir);
3435            FileUtils.deleteContentsAndDir(cacheBaseDir);
3436            return null;
3437        }
3438
3439        // The following is a workaround to aid development on non-numbered userdebug
3440        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3441        // the system partition is newer.
3442        //
3443        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3444        // that starts with "eng." to signify that this is an engineering build and not
3445        // destined for release.
3446        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3447            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3448
3449            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3450            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3451            // in general and should not be used for production changes. In this specific case,
3452            // we know that they will work.
3453            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3454            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3455                FileUtils.deleteContents(cacheBaseDir);
3456                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3457            }
3458        }
3459
3460        return cacheDir;
3461    }
3462
3463    @Override
3464    public boolean isFirstBoot() {
3465        // allow instant applications
3466        return mFirstBoot;
3467    }
3468
3469    @Override
3470    public boolean isOnlyCoreApps() {
3471        // allow instant applications
3472        return mOnlyCore;
3473    }
3474
3475    @Override
3476    public boolean isUpgrade() {
3477        // allow instant applications
3478        // The system property allows testing ota flow when upgraded to the same image.
3479        return mIsUpgrade || SystemProperties.getBoolean(
3480                "persist.pm.mock-upgrade", false /* default */);
3481    }
3482
3483    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3484        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3485
3486        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3487                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3488                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3489        if (matches.size() == 1) {
3490            return matches.get(0).getComponentInfo().packageName;
3491        } else if (matches.size() == 0) {
3492            Log.e(TAG, "There should probably be a verifier, but, none were found");
3493            return null;
3494        }
3495        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3496    }
3497
3498    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3499        synchronized (mPackages) {
3500            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3501            if (libraryEntry == null) {
3502                throw new IllegalStateException("Missing required shared library:" + name);
3503            }
3504            return libraryEntry.apk;
3505        }
3506    }
3507
3508    private @NonNull String getRequiredInstallerLPr() {
3509        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3510        intent.addCategory(Intent.CATEGORY_DEFAULT);
3511        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3512
3513        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3514                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3515                UserHandle.USER_SYSTEM);
3516        if (matches.size() == 1) {
3517            ResolveInfo resolveInfo = matches.get(0);
3518            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3519                throw new RuntimeException("The installer must be a privileged app");
3520            }
3521            return matches.get(0).getComponentInfo().packageName;
3522        } else {
3523            throw new RuntimeException("There must be exactly one installer; found " + matches);
3524        }
3525    }
3526
3527    private @NonNull String getRequiredUninstallerLPr() {
3528        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3529        intent.addCategory(Intent.CATEGORY_DEFAULT);
3530        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3531
3532        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3533                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3534                UserHandle.USER_SYSTEM);
3535        if (resolveInfo == null ||
3536                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3537            throw new RuntimeException("There must be exactly one uninstaller; found "
3538                    + resolveInfo);
3539        }
3540        return resolveInfo.getComponentInfo().packageName;
3541    }
3542
3543    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3544        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3545
3546        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3547                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3548                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3549        ResolveInfo best = null;
3550        final int N = matches.size();
3551        for (int i = 0; i < N; i++) {
3552            final ResolveInfo cur = matches.get(i);
3553            final String packageName = cur.getComponentInfo().packageName;
3554            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3555                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3556                continue;
3557            }
3558
3559            if (best == null || cur.priority > best.priority) {
3560                best = cur;
3561            }
3562        }
3563
3564        if (best != null) {
3565            return best.getComponentInfo().getComponentName();
3566        }
3567        Slog.w(TAG, "Intent filter verifier not found");
3568        return null;
3569    }
3570
3571    @Override
3572    public @Nullable ComponentName getInstantAppResolverComponent() {
3573        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3574            return null;
3575        }
3576        synchronized (mPackages) {
3577            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3578            if (instantAppResolver == null) {
3579                return null;
3580            }
3581            return instantAppResolver.first;
3582        }
3583    }
3584
3585    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3586        final String[] packageArray =
3587                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3588        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3589            if (DEBUG_INSTANT) {
3590                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3591            }
3592            return null;
3593        }
3594
3595        final int callingUid = Binder.getCallingUid();
3596        final int resolveFlags =
3597                MATCH_DIRECT_BOOT_AWARE
3598                | MATCH_DIRECT_BOOT_UNAWARE
3599                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3600        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3601        final Intent resolverIntent = new Intent(actionName);
3602        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3603                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3604        final int N = resolvers.size();
3605        if (N == 0) {
3606            if (DEBUG_INSTANT) {
3607                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3608            }
3609            return null;
3610        }
3611
3612        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3613        for (int i = 0; i < N; i++) {
3614            final ResolveInfo info = resolvers.get(i);
3615
3616            if (info.serviceInfo == null) {
3617                continue;
3618            }
3619
3620            final String packageName = info.serviceInfo.packageName;
3621            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3622                if (DEBUG_INSTANT) {
3623                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3624                            + " pkg: " + packageName + ", info:" + info);
3625                }
3626                continue;
3627            }
3628
3629            if (DEBUG_INSTANT) {
3630                Slog.v(TAG, "Ephemeral resolver found;"
3631                        + " pkg: " + packageName + ", info:" + info);
3632            }
3633            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3634        }
3635        if (DEBUG_INSTANT) {
3636            Slog.v(TAG, "Ephemeral resolver NOT found");
3637        }
3638        return null;
3639    }
3640
3641    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3642        String[] orderedActions = Build.IS_ENG
3643                ? new String[]{
3644                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE + "_TEST",
3645                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE}
3646                : new String[]{
3647                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE};
3648
3649        final int resolveFlags =
3650                MATCH_DIRECT_BOOT_AWARE
3651                        | MATCH_DIRECT_BOOT_UNAWARE
3652                        | Intent.FLAG_IGNORE_EPHEMERAL
3653                        | (!Build.IS_ENG ? MATCH_SYSTEM_ONLY : 0);
3654        final Intent intent = new Intent();
3655        intent.addCategory(Intent.CATEGORY_DEFAULT);
3656        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3657        List<ResolveInfo> matches = null;
3658        for (String action : orderedActions) {
3659            intent.setAction(action);
3660            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3661                    resolveFlags, UserHandle.USER_SYSTEM);
3662            if (matches.isEmpty()) {
3663                if (DEBUG_INSTANT) {
3664                    Slog.d(TAG, "Instant App installer not found with " + action);
3665                }
3666            } else {
3667                break;
3668            }
3669        }
3670        Iterator<ResolveInfo> iter = matches.iterator();
3671        while (iter.hasNext()) {
3672            final ResolveInfo rInfo = iter.next();
3673            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3674            if (ps != null) {
3675                final PermissionsState permissionsState = ps.getPermissionsState();
3676                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)
3677                        || Build.IS_ENG) {
3678                    continue;
3679                }
3680            }
3681            iter.remove();
3682        }
3683        if (matches.size() == 0) {
3684            return null;
3685        } else if (matches.size() == 1) {
3686            return (ActivityInfo) matches.get(0).getComponentInfo();
3687        } else {
3688            throw new RuntimeException(
3689                    "There must be at most one ephemeral installer; found " + matches);
3690        }
3691    }
3692
3693    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3694            @NonNull ComponentName resolver) {
3695        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3696                .addCategory(Intent.CATEGORY_DEFAULT)
3697                .setPackage(resolver.getPackageName());
3698        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3699        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3700                UserHandle.USER_SYSTEM);
3701        if (matches.isEmpty()) {
3702            return null;
3703        }
3704        return matches.get(0).getComponentInfo().getComponentName();
3705    }
3706
3707    private void primeDomainVerificationsLPw(int userId) {
3708        if (DEBUG_DOMAIN_VERIFICATION) {
3709            Slog.d(TAG, "Priming domain verifications in user " + userId);
3710        }
3711
3712        SystemConfig systemConfig = SystemConfig.getInstance();
3713        ArraySet<String> packages = systemConfig.getLinkedApps();
3714
3715        for (String packageName : packages) {
3716            PackageParser.Package pkg = mPackages.get(packageName);
3717            if (pkg != null) {
3718                if (!pkg.isSystem()) {
3719                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3720                    continue;
3721                }
3722
3723                ArraySet<String> domains = null;
3724                for (PackageParser.Activity a : pkg.activities) {
3725                    for (ActivityIntentInfo filter : a.intents) {
3726                        if (hasValidDomains(filter)) {
3727                            if (domains == null) {
3728                                domains = new ArraySet<String>();
3729                            }
3730                            domains.addAll(filter.getHostsList());
3731                        }
3732                    }
3733                }
3734
3735                if (domains != null && domains.size() > 0) {
3736                    if (DEBUG_DOMAIN_VERIFICATION) {
3737                        Slog.v(TAG, "      + " + packageName);
3738                    }
3739                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3740                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3741                    // and then 'always' in the per-user state actually used for intent resolution.
3742                    final IntentFilterVerificationInfo ivi;
3743                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3744                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3745                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3746                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3747                } else {
3748                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3749                            + "' does not handle web links");
3750                }
3751            } else {
3752                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3753            }
3754        }
3755
3756        scheduleWritePackageRestrictionsLocked(userId);
3757        scheduleWriteSettingsLocked();
3758    }
3759
3760    private void applyFactoryDefaultBrowserLPw(int userId) {
3761        // The default browser app's package name is stored in a string resource,
3762        // with a product-specific overlay used for vendor customization.
3763        String browserPkg = mContext.getResources().getString(
3764                com.android.internal.R.string.default_browser);
3765        if (!TextUtils.isEmpty(browserPkg)) {
3766            // non-empty string => required to be a known package
3767            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3768            if (ps == null) {
3769                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3770                browserPkg = null;
3771            } else {
3772                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3773            }
3774        }
3775
3776        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3777        // default.  If there's more than one, just leave everything alone.
3778        if (browserPkg == null) {
3779            calculateDefaultBrowserLPw(userId);
3780        }
3781    }
3782
3783    private void calculateDefaultBrowserLPw(int userId) {
3784        List<String> allBrowsers = resolveAllBrowserApps(userId);
3785        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3786        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3787    }
3788
3789    private List<String> resolveAllBrowserApps(int userId) {
3790        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3791        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3792                PackageManager.MATCH_ALL, userId);
3793
3794        final int count = list.size();
3795        List<String> result = new ArrayList<String>(count);
3796        for (int i=0; i<count; i++) {
3797            ResolveInfo info = list.get(i);
3798            if (info.activityInfo == null
3799                    || !info.handleAllWebDataURI
3800                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3801                    || result.contains(info.activityInfo.packageName)) {
3802                continue;
3803            }
3804            result.add(info.activityInfo.packageName);
3805        }
3806
3807        return result;
3808    }
3809
3810    private boolean packageIsBrowser(String packageName, int userId) {
3811        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3812                PackageManager.MATCH_ALL, userId);
3813        final int N = list.size();
3814        for (int i = 0; i < N; i++) {
3815            ResolveInfo info = list.get(i);
3816            if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) {
3817                return true;
3818            }
3819        }
3820        return false;
3821    }
3822
3823    private void checkDefaultBrowser() {
3824        final int myUserId = UserHandle.myUserId();
3825        final String packageName = getDefaultBrowserPackageName(myUserId);
3826        if (packageName != null) {
3827            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3828            if (info == null) {
3829                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3830                synchronized (mPackages) {
3831                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3832                }
3833            }
3834        }
3835    }
3836
3837    @Override
3838    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3839            throws RemoteException {
3840        try {
3841            return super.onTransact(code, data, reply, flags);
3842        } catch (RuntimeException e) {
3843            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3844                Slog.wtf(TAG, "Package Manager Crash", e);
3845            }
3846            throw e;
3847        }
3848    }
3849
3850    static int[] appendInts(int[] cur, int[] add) {
3851        if (add == null) return cur;
3852        if (cur == null) return add;
3853        final int N = add.length;
3854        for (int i=0; i<N; i++) {
3855            cur = appendInt(cur, add[i]);
3856        }
3857        return cur;
3858    }
3859
3860    /**
3861     * Returns whether or not a full application can see an instant application.
3862     * <p>
3863     * Currently, there are three cases in which this can occur:
3864     * <ol>
3865     * <li>The calling application is a "special" process. Special processes
3866     *     are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li>
3867     * <li>The calling application has the permission
3868     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li>
3869     * <li>The calling application is the default launcher on the
3870     *     system partition.</li>
3871     * </ol>
3872     */
3873    private boolean canViewInstantApps(int callingUid, int userId) {
3874        if (callingUid < Process.FIRST_APPLICATION_UID) {
3875            return true;
3876        }
3877        if (mContext.checkCallingOrSelfPermission(
3878                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3879            return true;
3880        }
3881        if (mContext.checkCallingOrSelfPermission(
3882                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3883            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3884            if (homeComponent != null
3885                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3886                return true;
3887            }
3888        }
3889        return false;
3890    }
3891
3892    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3893        if (!sUserManager.exists(userId)) return null;
3894        if (ps == null) {
3895            return null;
3896        }
3897        final int callingUid = Binder.getCallingUid();
3898        // Filter out ephemeral app metadata:
3899        //   * The system/shell/root can see metadata for any app
3900        //   * An installed app can see metadata for 1) other installed apps
3901        //     and 2) ephemeral apps that have explicitly interacted with it
3902        //   * Ephemeral apps can only see their own data and exposed installed apps
3903        //   * Holding a signature permission allows seeing instant apps
3904        if (filterAppAccessLPr(ps, callingUid, userId)) {
3905            return null;
3906        }
3907
3908        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3909                && ps.isSystem()) {
3910            flags |= MATCH_ANY_USER;
3911        }
3912
3913        final PackageUserState state = ps.readUserState(userId);
3914        PackageParser.Package p = ps.pkg;
3915        if (p != null) {
3916            final PermissionsState permissionsState = ps.getPermissionsState();
3917
3918            // Compute GIDs only if requested
3919            final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3920                    ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3921            // Compute granted permissions only if package has requested permissions
3922            final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3923                    ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3924
3925            PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3926                    ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3927
3928            if (packageInfo == null) {
3929                return null;
3930            }
3931
3932            packageInfo.packageName = packageInfo.applicationInfo.packageName =
3933                    resolveExternalPackageNameLPr(p);
3934
3935            return packageInfo;
3936        } else if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 && state.isAvailable(flags)) {
3937            PackageInfo pi = new PackageInfo();
3938            pi.packageName = ps.name;
3939            pi.setLongVersionCode(ps.versionCode);
3940            pi.sharedUserId = (ps.sharedUser != null) ? ps.sharedUser.name : null;
3941            pi.firstInstallTime = ps.firstInstallTime;
3942            pi.lastUpdateTime = ps.lastUpdateTime;
3943
3944            ApplicationInfo ai = new ApplicationInfo();
3945            ai.packageName = ps.name;
3946            ai.uid = UserHandle.getUid(userId, ps.appId);
3947            ai.primaryCpuAbi = ps.primaryCpuAbiString;
3948            ai.secondaryCpuAbi = ps.secondaryCpuAbiString;
3949            ai.versionCode = ps.versionCode;
3950            ai.flags = ps.pkgFlags;
3951            ai.privateFlags = ps.pkgPrivateFlags;
3952            pi.applicationInfo = PackageParser.generateApplicationInfo(ai, flags, state, userId);
3953
3954            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "ps.pkg is n/a for ["
3955                    + ps.name + "]. Provides a minimum info.");
3956            return pi;
3957        } else {
3958            return null;
3959        }
3960    }
3961
3962    @Override
3963    public void checkPackageStartable(String packageName, int userId) {
3964        final int callingUid = Binder.getCallingUid();
3965        if (getInstantAppPackageName(callingUid) != null) {
3966            throw new SecurityException("Instant applications don't have access to this method");
3967        }
3968        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3969        synchronized (mPackages) {
3970            final PackageSetting ps = mSettings.mPackages.get(packageName);
3971            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3972                throw new SecurityException("Package " + packageName + " was not found!");
3973            }
3974
3975            if (!ps.getInstalled(userId)) {
3976                throw new SecurityException(
3977                        "Package " + packageName + " was not installed for user " + userId + "!");
3978            }
3979
3980            if (mSafeMode && !ps.isSystem()) {
3981                throw new SecurityException("Package " + packageName + " not a system app!");
3982            }
3983
3984            if (mFrozenPackages.contains(packageName)) {
3985                throw new SecurityException("Package " + packageName + " is currently frozen!");
3986            }
3987
3988            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3989                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3990            }
3991        }
3992    }
3993
3994    @Override
3995    public boolean isPackageAvailable(String packageName, int userId) {
3996        if (!sUserManager.exists(userId)) return false;
3997        final int callingUid = Binder.getCallingUid();
3998        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
3999                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
4000        synchronized (mPackages) {
4001            PackageParser.Package p = mPackages.get(packageName);
4002            if (p != null) {
4003                final PackageSetting ps = (PackageSetting) p.mExtras;
4004                if (filterAppAccessLPr(ps, callingUid, userId)) {
4005                    return false;
4006                }
4007                if (ps != null) {
4008                    final PackageUserState state = ps.readUserState(userId);
4009                    if (state != null) {
4010                        return PackageParser.isAvailable(state);
4011                    }
4012                }
4013            }
4014        }
4015        return false;
4016    }
4017
4018    @Override
4019    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
4020        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
4021                flags, Binder.getCallingUid(), userId);
4022    }
4023
4024    @Override
4025    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
4026            int flags, int userId) {
4027        return getPackageInfoInternal(versionedPackage.getPackageName(),
4028                versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId);
4029    }
4030
4031    /**
4032     * Important: The provided filterCallingUid is used exclusively to filter out packages
4033     * that can be seen based on user state. It's typically the original caller uid prior
4034     * to clearing. Because it can only be provided by trusted code, it's value can be
4035     * trusted and will be used as-is; unlike userId which will be validated by this method.
4036     */
4037    private PackageInfo getPackageInfoInternal(String packageName, long versionCode,
4038            int flags, int filterCallingUid, int userId) {
4039        if (!sUserManager.exists(userId)) return null;
4040        flags = updateFlagsForPackage(flags, userId, packageName);
4041        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4042                false /* requireFullPermission */, false /* checkShell */, "get package info");
4043
4044        // reader
4045        synchronized (mPackages) {
4046            // Normalize package name to handle renamed packages and static libs
4047            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
4048
4049            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
4050            if (matchFactoryOnly) {
4051                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
4052                if (ps != null) {
4053                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4054                        return null;
4055                    }
4056                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4057                        return null;
4058                    }
4059                    return generatePackageInfo(ps, flags, userId);
4060                }
4061            }
4062
4063            PackageParser.Package p = mPackages.get(packageName);
4064            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
4065                return null;
4066            }
4067            if (DEBUG_PACKAGE_INFO)
4068                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
4069            if (p != null) {
4070                final PackageSetting ps = (PackageSetting) p.mExtras;
4071                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4072                    return null;
4073                }
4074                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
4075                    return null;
4076                }
4077                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
4078            }
4079            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
4080                final PackageSetting ps = mSettings.mPackages.get(packageName);
4081                if (ps == null) return null;
4082                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4083                    return null;
4084                }
4085                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4086                    return null;
4087                }
4088                return generatePackageInfo(ps, flags, userId);
4089            }
4090        }
4091        return null;
4092    }
4093
4094    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
4095        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
4096            return true;
4097        }
4098        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
4099            return true;
4100        }
4101        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4102            return true;
4103        }
4104        return false;
4105    }
4106
4107    private boolean isComponentVisibleToInstantApp(
4108            @Nullable ComponentName component, @ComponentType int type) {
4109        if (type == TYPE_ACTIVITY) {
4110            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4111            if (activity == null) {
4112                return false;
4113            }
4114            final boolean visibleToInstantApp =
4115                    (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
4116            final boolean explicitlyVisibleToInstantApp =
4117                    (activity.info.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
4118            return visibleToInstantApp && explicitlyVisibleToInstantApp;
4119        } else if (type == TYPE_RECEIVER) {
4120            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4121            if (activity == null) {
4122                return false;
4123            }
4124            final boolean visibleToInstantApp =
4125                    (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
4126            final boolean explicitlyVisibleToInstantApp =
4127                    (activity.info.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
4128            return visibleToInstantApp && !explicitlyVisibleToInstantApp;
4129        } else if (type == TYPE_SERVICE) {
4130            final PackageParser.Service service = mServices.mServices.get(component);
4131            return service != null
4132                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4133                    : false;
4134        } else if (type == TYPE_PROVIDER) {
4135            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4136            return provider != null
4137                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4138                    : false;
4139        } else if (type == TYPE_UNKNOWN) {
4140            return isComponentVisibleToInstantApp(component);
4141        }
4142        return false;
4143    }
4144
4145    /**
4146     * Returns whether or not access to the application should be filtered.
4147     * <p>
4148     * Access may be limited based upon whether the calling or target applications
4149     * are instant applications.
4150     *
4151     * @see #canAccessInstantApps(int)
4152     */
4153    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4154            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4155        // if we're in an isolated process, get the real calling UID
4156        if (Process.isIsolated(callingUid)) {
4157            callingUid = mIsolatedOwners.get(callingUid);
4158        }
4159        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4160        final boolean callerIsInstantApp = instantAppPkgName != null;
4161        if (ps == null) {
4162            if (callerIsInstantApp) {
4163                // pretend the application exists, but, needs to be filtered
4164                return true;
4165            }
4166            return false;
4167        }
4168        // if the target and caller are the same application, don't filter
4169        if (isCallerSameApp(ps.name, callingUid)) {
4170            return false;
4171        }
4172        if (callerIsInstantApp) {
4173            // both caller and target are both instant, but, different applications, filter
4174            if (ps.getInstantApp(userId)) {
4175                return true;
4176            }
4177            // request for a specific component; if it hasn't been explicitly exposed through
4178            // property or instrumentation target, filter
4179            if (component != null) {
4180                final PackageParser.Instrumentation instrumentation =
4181                        mInstrumentation.get(component);
4182                if (instrumentation != null
4183                        && isCallerSameApp(instrumentation.info.targetPackage, callingUid)) {
4184                    return false;
4185                }
4186                return !isComponentVisibleToInstantApp(component, componentType);
4187            }
4188            // request for application; if no components have been explicitly exposed, filter
4189            return !ps.pkg.visibleToInstantApps;
4190        }
4191        if (ps.getInstantApp(userId)) {
4192            // caller can see all components of all instant applications, don't filter
4193            if (canViewInstantApps(callingUid, userId)) {
4194                return false;
4195            }
4196            // request for a specific instant application component, filter
4197            if (component != null) {
4198                return true;
4199            }
4200            // request for an instant application; if the caller hasn't been granted access, filter
4201            return !mInstantAppRegistry.isInstantAccessGranted(
4202                    userId, UserHandle.getAppId(callingUid), ps.appId);
4203        }
4204        return false;
4205    }
4206
4207    /**
4208     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4209     */
4210    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4211        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4212    }
4213
4214    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4215            int flags) {
4216        // Callers can access only the libs they depend on, otherwise they need to explicitly
4217        // ask for the shared libraries given the caller is allowed to access all static libs.
4218        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4219            // System/shell/root get to see all static libs
4220            final int appId = UserHandle.getAppId(uid);
4221            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4222                    || appId == Process.ROOT_UID) {
4223                return false;
4224            }
4225        }
4226
4227        // No package means no static lib as it is always on internal storage
4228        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4229            return false;
4230        }
4231
4232        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4233                ps.pkg.staticSharedLibVersion);
4234        if (libEntry == null) {
4235            return false;
4236        }
4237
4238        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4239        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4240        if (uidPackageNames == null) {
4241            return true;
4242        }
4243
4244        for (String uidPackageName : uidPackageNames) {
4245            if (ps.name.equals(uidPackageName)) {
4246                return false;
4247            }
4248            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4249            if (uidPs != null) {
4250                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4251                        libEntry.info.getName());
4252                if (index < 0) {
4253                    continue;
4254                }
4255                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) {
4256                    return false;
4257                }
4258            }
4259        }
4260        return true;
4261    }
4262
4263    @Override
4264    public String[] currentToCanonicalPackageNames(String[] names) {
4265        final int callingUid = Binder.getCallingUid();
4266        if (getInstantAppPackageName(callingUid) != null) {
4267            return names;
4268        }
4269        final String[] out = new String[names.length];
4270        // reader
4271        synchronized (mPackages) {
4272            final int callingUserId = UserHandle.getUserId(callingUid);
4273            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4274            for (int i=names.length-1; i>=0; i--) {
4275                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4276                boolean translateName = false;
4277                if (ps != null && ps.realName != null) {
4278                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4279                    translateName = !targetIsInstantApp
4280                            || canViewInstantApps
4281                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4282                                    UserHandle.getAppId(callingUid), ps.appId);
4283                }
4284                out[i] = translateName ? ps.realName : names[i];
4285            }
4286        }
4287        return out;
4288    }
4289
4290    @Override
4291    public String[] canonicalToCurrentPackageNames(String[] names) {
4292        final int callingUid = Binder.getCallingUid();
4293        if (getInstantAppPackageName(callingUid) != null) {
4294            return names;
4295        }
4296        final String[] out = new String[names.length];
4297        // reader
4298        synchronized (mPackages) {
4299            final int callingUserId = UserHandle.getUserId(callingUid);
4300            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4301            for (int i=names.length-1; i>=0; i--) {
4302                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4303                boolean translateName = false;
4304                if (cur != null) {
4305                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4306                    final boolean targetIsInstantApp =
4307                            ps != null && ps.getInstantApp(callingUserId);
4308                    translateName = !targetIsInstantApp
4309                            || canViewInstantApps
4310                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4311                                    UserHandle.getAppId(callingUid), ps.appId);
4312                }
4313                out[i] = translateName ? cur : names[i];
4314            }
4315        }
4316        return out;
4317    }
4318
4319    @Override
4320    public int getPackageUid(String packageName, int flags, int userId) {
4321        if (!sUserManager.exists(userId)) return -1;
4322        final int callingUid = Binder.getCallingUid();
4323        flags = updateFlagsForPackage(flags, userId, packageName);
4324        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4325                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4326
4327        // reader
4328        synchronized (mPackages) {
4329            final PackageParser.Package p = mPackages.get(packageName);
4330            if (p != null && p.isMatch(flags)) {
4331                PackageSetting ps = (PackageSetting) p.mExtras;
4332                if (filterAppAccessLPr(ps, callingUid, userId)) {
4333                    return -1;
4334                }
4335                return UserHandle.getUid(userId, p.applicationInfo.uid);
4336            }
4337            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4338                final PackageSetting ps = mSettings.mPackages.get(packageName);
4339                if (ps != null && ps.isMatch(flags)
4340                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4341                    return UserHandle.getUid(userId, ps.appId);
4342                }
4343            }
4344        }
4345
4346        return -1;
4347    }
4348
4349    @Override
4350    public int[] getPackageGids(String packageName, int flags, int userId) {
4351        if (!sUserManager.exists(userId)) return null;
4352        final int callingUid = Binder.getCallingUid();
4353        flags = updateFlagsForPackage(flags, userId, packageName);
4354        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4355                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4356
4357        // reader
4358        synchronized (mPackages) {
4359            final PackageParser.Package p = mPackages.get(packageName);
4360            if (p != null && p.isMatch(flags)) {
4361                PackageSetting ps = (PackageSetting) p.mExtras;
4362                if (filterAppAccessLPr(ps, callingUid, userId)) {
4363                    return null;
4364                }
4365                // TODO: Shouldn't this be checking for package installed state for userId and
4366                // return null?
4367                return ps.getPermissionsState().computeGids(userId);
4368            }
4369            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4370                final PackageSetting ps = mSettings.mPackages.get(packageName);
4371                if (ps != null && ps.isMatch(flags)
4372                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4373                    return ps.getPermissionsState().computeGids(userId);
4374                }
4375            }
4376        }
4377
4378        return null;
4379    }
4380
4381    @Override
4382    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4383        return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4384    }
4385
4386    @Override
4387    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4388            int flags) {
4389        final List<PermissionInfo> permissionList =
4390                mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid());
4391        return (permissionList == null) ? null : new ParceledListSlice<>(permissionList);
4392    }
4393
4394    @Override
4395    public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) {
4396        return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid());
4397    }
4398
4399    @Override
4400    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4401        final List<PermissionGroupInfo> permissionList =
4402                mPermissionManager.getAllPermissionGroups(flags, getCallingUid());
4403        return (permissionList == null)
4404                ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList);
4405    }
4406
4407    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4408            int filterCallingUid, int userId) {
4409        if (!sUserManager.exists(userId)) return null;
4410        PackageSetting ps = mSettings.mPackages.get(packageName);
4411        if (ps != null) {
4412            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4413                return null;
4414            }
4415            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4416                return null;
4417            }
4418            if (ps.pkg == null) {
4419                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4420                if (pInfo != null) {
4421                    return pInfo.applicationInfo;
4422                }
4423                return null;
4424            }
4425            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4426                    ps.readUserState(userId), userId);
4427            if (ai != null) {
4428                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4429            }
4430            return ai;
4431        }
4432        return null;
4433    }
4434
4435    @Override
4436    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4437        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4438    }
4439
4440    /**
4441     * Important: The provided filterCallingUid is used exclusively to filter out applications
4442     * that can be seen based on user state. It's typically the original caller uid prior
4443     * to clearing. Because it can only be provided by trusted code, it's value can be
4444     * trusted and will be used as-is; unlike userId which will be validated by this method.
4445     */
4446    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4447            int filterCallingUid, int userId) {
4448        if (!sUserManager.exists(userId)) return null;
4449        flags = updateFlagsForApplication(flags, userId, packageName);
4450        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4451                false /* requireFullPermission */, false /* checkShell */, "get application info");
4452
4453        // writer
4454        synchronized (mPackages) {
4455            // Normalize package name to handle renamed packages and static libs
4456            packageName = resolveInternalPackageNameLPr(packageName,
4457                    PackageManager.VERSION_CODE_HIGHEST);
4458
4459            PackageParser.Package p = mPackages.get(packageName);
4460            if (DEBUG_PACKAGE_INFO) Log.v(
4461                    TAG, "getApplicationInfo " + packageName
4462                    + ": " + p);
4463            if (p != null) {
4464                PackageSetting ps = mSettings.mPackages.get(packageName);
4465                if (ps == null) return null;
4466                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4467                    return null;
4468                }
4469                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4470                    return null;
4471                }
4472                // Note: isEnabledLP() does not apply here - always return info
4473                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4474                        p, flags, ps.readUserState(userId), userId);
4475                if (ai != null) {
4476                    ai.packageName = resolveExternalPackageNameLPr(p);
4477                }
4478                return ai;
4479            }
4480            if ("android".equals(packageName)||"system".equals(packageName)) {
4481                return mAndroidApplication;
4482            }
4483            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4484                // Already generates the external package name
4485                return generateApplicationInfoFromSettingsLPw(packageName,
4486                        flags, filterCallingUid, userId);
4487            }
4488        }
4489        return null;
4490    }
4491
4492    private String normalizePackageNameLPr(String packageName) {
4493        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4494        return normalizedPackageName != null ? normalizedPackageName : packageName;
4495    }
4496
4497    @Override
4498    public void deletePreloadsFileCache() {
4499        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4500            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4501        }
4502        File dir = Environment.getDataPreloadsFileCacheDirectory();
4503        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4504        FileUtils.deleteContents(dir);
4505    }
4506
4507    @Override
4508    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4509            final int storageFlags, final IPackageDataObserver observer) {
4510        mContext.enforceCallingOrSelfPermission(
4511                android.Manifest.permission.CLEAR_APP_CACHE, null);
4512        mHandler.post(() -> {
4513            boolean success = false;
4514            try {
4515                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4516                success = true;
4517            } catch (IOException e) {
4518                Slog.w(TAG, e);
4519            }
4520            if (observer != null) {
4521                try {
4522                    observer.onRemoveCompleted(null, success);
4523                } catch (RemoteException e) {
4524                    Slog.w(TAG, e);
4525                }
4526            }
4527        });
4528    }
4529
4530    @Override
4531    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4532            final int storageFlags, final IntentSender pi) {
4533        mContext.enforceCallingOrSelfPermission(
4534                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4535        mHandler.post(() -> {
4536            boolean success = false;
4537            try {
4538                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4539                success = true;
4540            } catch (IOException e) {
4541                Slog.w(TAG, e);
4542            }
4543            if (pi != null) {
4544                try {
4545                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4546                } catch (SendIntentException e) {
4547                    Slog.w(TAG, e);
4548                }
4549            }
4550        });
4551    }
4552
4553    /**
4554     * Blocking call to clear various types of cached data across the system
4555     * until the requested bytes are available.
4556     */
4557    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4558        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4559        final File file = storage.findPathForUuid(volumeUuid);
4560        if (file.getUsableSpace() >= bytes) return;
4561
4562        if (ENABLE_FREE_CACHE_V2) {
4563            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4564                    volumeUuid);
4565            final boolean aggressive = (storageFlags
4566                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4567            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4568
4569            // 1. Pre-flight to determine if we have any chance to succeed
4570            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4571            if (internalVolume && (aggressive || SystemProperties
4572                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4573                deletePreloadsFileCache();
4574                if (file.getUsableSpace() >= bytes) return;
4575            }
4576
4577            // 3. Consider parsed APK data (aggressive only)
4578            if (internalVolume && aggressive) {
4579                FileUtils.deleteContents(mCacheDir);
4580                if (file.getUsableSpace() >= bytes) return;
4581            }
4582
4583            // 4. Consider cached app data (above quotas)
4584            try {
4585                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4586                        Installer.FLAG_FREE_CACHE_V2);
4587            } catch (InstallerException ignored) {
4588            }
4589            if (file.getUsableSpace() >= bytes) return;
4590
4591            // 5. Consider shared libraries with refcount=0 and age>min cache period
4592            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4593                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4594                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4595                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4596                return;
4597            }
4598
4599            // 6. Consider dexopt output (aggressive only)
4600            // TODO: Implement
4601
4602            // 7. Consider installed instant apps unused longer than min cache period
4603            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4604                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4605                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4606                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4607                return;
4608            }
4609
4610            // 8. Consider cached app data (below quotas)
4611            try {
4612                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4613                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4614            } catch (InstallerException ignored) {
4615            }
4616            if (file.getUsableSpace() >= bytes) return;
4617
4618            // 9. Consider DropBox entries
4619            // TODO: Implement
4620
4621            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4622            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4623                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4624                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4625                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4626                return;
4627            }
4628        } else {
4629            try {
4630                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4631            } catch (InstallerException ignored) {
4632            }
4633            if (file.getUsableSpace() >= bytes) return;
4634        }
4635
4636        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4637    }
4638
4639    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4640            throws IOException {
4641        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4642        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4643
4644        List<VersionedPackage> packagesToDelete = null;
4645        final long now = System.currentTimeMillis();
4646
4647        synchronized (mPackages) {
4648            final int[] allUsers = sUserManager.getUserIds();
4649            final int libCount = mSharedLibraries.size();
4650            for (int i = 0; i < libCount; i++) {
4651                final LongSparseArray<SharedLibraryEntry> versionedLib
4652                        = mSharedLibraries.valueAt(i);
4653                if (versionedLib == null) {
4654                    continue;
4655                }
4656                final int versionCount = versionedLib.size();
4657                for (int j = 0; j < versionCount; j++) {
4658                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4659                    // Skip packages that are not static shared libs.
4660                    if (!libInfo.isStatic()) {
4661                        break;
4662                    }
4663                    // Important: We skip static shared libs used for some user since
4664                    // in such a case we need to keep the APK on the device. The check for
4665                    // a lib being used for any user is performed by the uninstall call.
4666                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4667                    // Resolve the package name - we use synthetic package names internally
4668                    final String internalPackageName = resolveInternalPackageNameLPr(
4669                            declaringPackage.getPackageName(),
4670                            declaringPackage.getLongVersionCode());
4671                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4672                    // Skip unused static shared libs cached less than the min period
4673                    // to prevent pruning a lib needed by a subsequently installed package.
4674                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4675                        continue;
4676                    }
4677                    if (packagesToDelete == null) {
4678                        packagesToDelete = new ArrayList<>();
4679                    }
4680                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4681                            declaringPackage.getLongVersionCode()));
4682                }
4683            }
4684        }
4685
4686        if (packagesToDelete != null) {
4687            final int packageCount = packagesToDelete.size();
4688            for (int i = 0; i < packageCount; i++) {
4689                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4690                // Delete the package synchronously (will fail of the lib used for any user).
4691                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(),
4692                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4693                                == PackageManager.DELETE_SUCCEEDED) {
4694                    if (volume.getUsableSpace() >= neededSpace) {
4695                        return true;
4696                    }
4697                }
4698            }
4699        }
4700
4701        return false;
4702    }
4703
4704    /**
4705     * Update given flags based on encryption status of current user.
4706     */
4707    private int updateFlags(int flags, int userId) {
4708        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4709                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4710            // Caller expressed an explicit opinion about what encryption
4711            // aware/unaware components they want to see, so fall through and
4712            // give them what they want
4713        } else {
4714            // Caller expressed no opinion, so match based on user state
4715            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4716                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4717            } else {
4718                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4719            }
4720        }
4721        return flags;
4722    }
4723
4724    private UserManagerInternal getUserManagerInternal() {
4725        if (mUserManagerInternal == null) {
4726            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4727        }
4728        return mUserManagerInternal;
4729    }
4730
4731    private ActivityManagerInternal getActivityManagerInternal() {
4732        if (mActivityManagerInternal == null) {
4733            mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
4734        }
4735        return mActivityManagerInternal;
4736    }
4737
4738
4739    private DeviceIdleController.LocalService getDeviceIdleController() {
4740        if (mDeviceIdleController == null) {
4741            mDeviceIdleController =
4742                    LocalServices.getService(DeviceIdleController.LocalService.class);
4743        }
4744        return mDeviceIdleController;
4745    }
4746
4747    /**
4748     * Update given flags when being used to request {@link PackageInfo}.
4749     */
4750    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4751        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4752        boolean triaged = true;
4753        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4754                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4755            // Caller is asking for component details, so they'd better be
4756            // asking for specific encryption matching behavior, or be triaged
4757            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4758                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4759                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4760                triaged = false;
4761            }
4762        }
4763        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4764                | PackageManager.MATCH_SYSTEM_ONLY
4765                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4766            triaged = false;
4767        }
4768        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4769            mPermissionManager.enforceCrossUserPermission(
4770                    Binder.getCallingUid(), userId, false, false,
4771                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4772                    + Debug.getCallers(5));
4773        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4774                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4775            // If the caller wants all packages and has a restricted profile associated with it,
4776            // then match all users. This is to make sure that launchers that need to access work
4777            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4778            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4779            flags |= PackageManager.MATCH_ANY_USER;
4780        }
4781        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4782            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4783                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4784        }
4785        return updateFlags(flags, userId);
4786    }
4787
4788    /**
4789     * Update given flags when being used to request {@link ApplicationInfo}.
4790     */
4791    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4792        return updateFlagsForPackage(flags, userId, cookie);
4793    }
4794
4795    /**
4796     * Update given flags when being used to request {@link ComponentInfo}.
4797     */
4798    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4799        if (cookie instanceof Intent) {
4800            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4801                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4802            }
4803        }
4804
4805        boolean triaged = true;
4806        // Caller is asking for component details, so they'd better be
4807        // asking for specific encryption matching behavior, or be triaged
4808        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4809                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4810                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4811            triaged = false;
4812        }
4813        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4814            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4815                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4816        }
4817
4818        return updateFlags(flags, userId);
4819    }
4820
4821    /**
4822     * Update given intent when being used to request {@link ResolveInfo}.
4823     */
4824    private Intent updateIntentForResolve(Intent intent) {
4825        if (intent.getSelector() != null) {
4826            intent = intent.getSelector();
4827        }
4828        if (DEBUG_PREFERRED) {
4829            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4830        }
4831        return intent;
4832    }
4833
4834    /**
4835     * Update given flags when being used to request {@link ResolveInfo}.
4836     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4837     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4838     * flag set. However, this flag is only honoured in three circumstances:
4839     * <ul>
4840     * <li>when called from a system process</li>
4841     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4842     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4843     * action and a {@code android.intent.category.BROWSABLE} category</li>
4844     * </ul>
4845     */
4846    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4847        return updateFlagsForResolve(flags, userId, intent, callingUid,
4848                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4849    }
4850    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4851            boolean wantInstantApps) {
4852        return updateFlagsForResolve(flags, userId, intent, callingUid,
4853                wantInstantApps, false /*onlyExposedExplicitly*/);
4854    }
4855    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4856            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4857        // Safe mode means we shouldn't match any third-party components
4858        if (mSafeMode) {
4859            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4860        }
4861        if (getInstantAppPackageName(callingUid) != null) {
4862            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4863            if (onlyExposedExplicitly) {
4864                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4865            }
4866            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4867            flags |= PackageManager.MATCH_INSTANT;
4868        } else {
4869            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4870            final boolean allowMatchInstant = wantInstantApps
4871                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4872            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4873                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4874            if (!allowMatchInstant) {
4875                flags &= ~PackageManager.MATCH_INSTANT;
4876            }
4877        }
4878        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4879    }
4880
4881    @Override
4882    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4883        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4884    }
4885
4886    /**
4887     * Important: The provided filterCallingUid is used exclusively to filter out activities
4888     * that can be seen based on user state. It's typically the original caller uid prior
4889     * to clearing. Because it can only be provided by trusted code, it's value can be
4890     * trusted and will be used as-is; unlike userId which will be validated by this method.
4891     */
4892    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4893            int filterCallingUid, int userId) {
4894        if (!sUserManager.exists(userId)) return null;
4895        flags = updateFlagsForComponent(flags, userId, component);
4896
4897        if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) {
4898            mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4899                    false /* requireFullPermission */, false /* checkShell */, "get activity info");
4900        }
4901
4902        synchronized (mPackages) {
4903            PackageParser.Activity a = mActivities.mActivities.get(component);
4904
4905            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4906            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4907                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4908                if (ps == null) return null;
4909                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4910                    return null;
4911                }
4912                return PackageParser.generateActivityInfo(
4913                        a, flags, ps.readUserState(userId), userId);
4914            }
4915            if (mResolveComponentName.equals(component)) {
4916                return PackageParser.generateActivityInfo(
4917                        mResolveActivity, flags, new PackageUserState(), userId);
4918            }
4919        }
4920        return null;
4921    }
4922
4923    private boolean isRecentsAccessingChildProfiles(int callingUid, int targetUserId) {
4924        if (!getActivityManagerInternal().isCallerRecents(callingUid)) {
4925            return false;
4926        }
4927        final long token = Binder.clearCallingIdentity();
4928        try {
4929            final int callingUserId = UserHandle.getUserId(callingUid);
4930            if (ActivityManager.getCurrentUser() != callingUserId) {
4931                return false;
4932            }
4933            return sUserManager.isSameProfileGroup(callingUserId, targetUserId);
4934        } finally {
4935            Binder.restoreCallingIdentity(token);
4936        }
4937    }
4938
4939    @Override
4940    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4941            String resolvedType) {
4942        synchronized (mPackages) {
4943            if (component.equals(mResolveComponentName)) {
4944                // The resolver supports EVERYTHING!
4945                return true;
4946            }
4947            final int callingUid = Binder.getCallingUid();
4948            final int callingUserId = UserHandle.getUserId(callingUid);
4949            PackageParser.Activity a = mActivities.mActivities.get(component);
4950            if (a == null) {
4951                return false;
4952            }
4953            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4954            if (ps == null) {
4955                return false;
4956            }
4957            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4958                return false;
4959            }
4960            for (int i=0; i<a.intents.size(); i++) {
4961                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4962                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4963                    return true;
4964                }
4965            }
4966            return false;
4967        }
4968    }
4969
4970    @Override
4971    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4972        if (!sUserManager.exists(userId)) return null;
4973        final int callingUid = Binder.getCallingUid();
4974        flags = updateFlagsForComponent(flags, userId, component);
4975        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4976                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4977        synchronized (mPackages) {
4978            PackageParser.Activity a = mReceivers.mActivities.get(component);
4979            if (DEBUG_PACKAGE_INFO) Log.v(
4980                TAG, "getReceiverInfo " + component + ": " + a);
4981            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4982                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4983                if (ps == null) return null;
4984                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4985                    return null;
4986                }
4987                return PackageParser.generateActivityInfo(
4988                        a, flags, ps.readUserState(userId), userId);
4989            }
4990        }
4991        return null;
4992    }
4993
4994    @Override
4995    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4996            int flags, int userId) {
4997        if (!sUserManager.exists(userId)) return null;
4998        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4999        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5000            return null;
5001        }
5002
5003        flags = updateFlagsForPackage(flags, userId, null);
5004
5005        final boolean canSeeStaticLibraries =
5006                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
5007                        == PERMISSION_GRANTED
5008                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
5009                        == PERMISSION_GRANTED
5010                || canRequestPackageInstallsInternal(packageName,
5011                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
5012                        false  /* throwIfPermNotDeclared*/)
5013                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
5014                        == PERMISSION_GRANTED;
5015
5016        synchronized (mPackages) {
5017            List<SharedLibraryInfo> result = null;
5018
5019            final int libCount = mSharedLibraries.size();
5020            for (int i = 0; i < libCount; i++) {
5021                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5022                if (versionedLib == null) {
5023                    continue;
5024                }
5025
5026                final int versionCount = versionedLib.size();
5027                for (int j = 0; j < versionCount; j++) {
5028                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
5029                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
5030                        break;
5031                    }
5032                    final long identity = Binder.clearCallingIdentity();
5033                    try {
5034                        PackageInfo packageInfo = getPackageInfoVersioned(
5035                                libInfo.getDeclaringPackage(), flags
5036                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
5037                        if (packageInfo == null) {
5038                            continue;
5039                        }
5040                    } finally {
5041                        Binder.restoreCallingIdentity(identity);
5042                    }
5043
5044                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
5045                            libInfo.getLongVersion(), libInfo.getType(),
5046                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
5047                            flags, userId));
5048
5049                    if (result == null) {
5050                        result = new ArrayList<>();
5051                    }
5052                    result.add(resLibInfo);
5053                }
5054            }
5055
5056            return result != null ? new ParceledListSlice<>(result) : null;
5057        }
5058    }
5059
5060    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
5061            SharedLibraryInfo libInfo, int flags, int userId) {
5062        List<VersionedPackage> versionedPackages = null;
5063        final int packageCount = mSettings.mPackages.size();
5064        for (int i = 0; i < packageCount; i++) {
5065            PackageSetting ps = mSettings.mPackages.valueAt(i);
5066
5067            if (ps == null) {
5068                continue;
5069            }
5070
5071            if (!ps.getUserState().get(userId).isAvailable(flags)) {
5072                continue;
5073            }
5074
5075            final String libName = libInfo.getName();
5076            if (libInfo.isStatic()) {
5077                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
5078                if (libIdx < 0) {
5079                    continue;
5080                }
5081                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) {
5082                    continue;
5083                }
5084                if (versionedPackages == null) {
5085                    versionedPackages = new ArrayList<>();
5086                }
5087                // If the dependent is a static shared lib, use the public package name
5088                String dependentPackageName = ps.name;
5089                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5090                    dependentPackageName = ps.pkg.manifestPackageName;
5091                }
5092                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5093            } else if (ps.pkg != null) {
5094                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5095                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5096                    if (versionedPackages == null) {
5097                        versionedPackages = new ArrayList<>();
5098                    }
5099                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5100                }
5101            }
5102        }
5103
5104        return versionedPackages;
5105    }
5106
5107    @Override
5108    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5109        if (!sUserManager.exists(userId)) return null;
5110        final int callingUid = Binder.getCallingUid();
5111        flags = updateFlagsForComponent(flags, userId, component);
5112        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5113                false /* requireFullPermission */, false /* checkShell */, "get service info");
5114        synchronized (mPackages) {
5115            PackageParser.Service s = mServices.mServices.get(component);
5116            if (DEBUG_PACKAGE_INFO) Log.v(
5117                TAG, "getServiceInfo " + component + ": " + s);
5118            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5119                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5120                if (ps == null) return null;
5121                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5122                    return null;
5123                }
5124                return PackageParser.generateServiceInfo(
5125                        s, flags, ps.readUserState(userId), userId);
5126            }
5127        }
5128        return null;
5129    }
5130
5131    @Override
5132    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5133        if (!sUserManager.exists(userId)) return null;
5134        final int callingUid = Binder.getCallingUid();
5135        flags = updateFlagsForComponent(flags, userId, component);
5136        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5137                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5138        synchronized (mPackages) {
5139            PackageParser.Provider p = mProviders.mProviders.get(component);
5140            if (DEBUG_PACKAGE_INFO) Log.v(
5141                TAG, "getProviderInfo " + component + ": " + p);
5142            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5143                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5144                if (ps == null) return null;
5145                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5146                    return null;
5147                }
5148                return PackageParser.generateProviderInfo(
5149                        p, flags, ps.readUserState(userId), userId);
5150            }
5151        }
5152        return null;
5153    }
5154
5155    @Override
5156    public String[] getSystemSharedLibraryNames() {
5157        // allow instant applications
5158        synchronized (mPackages) {
5159            Set<String> libs = null;
5160            final int libCount = mSharedLibraries.size();
5161            for (int i = 0; i < libCount; i++) {
5162                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5163                if (versionedLib == null) {
5164                    continue;
5165                }
5166                final int versionCount = versionedLib.size();
5167                for (int j = 0; j < versionCount; j++) {
5168                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5169                    if (!libEntry.info.isStatic()) {
5170                        if (libs == null) {
5171                            libs = new ArraySet<>();
5172                        }
5173                        libs.add(libEntry.info.getName());
5174                        break;
5175                    }
5176                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5177                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5178                            UserHandle.getUserId(Binder.getCallingUid()),
5179                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5180                        if (libs == null) {
5181                            libs = new ArraySet<>();
5182                        }
5183                        libs.add(libEntry.info.getName());
5184                        break;
5185                    }
5186                }
5187            }
5188
5189            if (libs != null) {
5190                String[] libsArray = new String[libs.size()];
5191                libs.toArray(libsArray);
5192                return libsArray;
5193            }
5194
5195            return null;
5196        }
5197    }
5198
5199    @Override
5200    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5201        // allow instant applications
5202        synchronized (mPackages) {
5203            return mServicesSystemSharedLibraryPackageName;
5204        }
5205    }
5206
5207    @Override
5208    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5209        // allow instant applications
5210        synchronized (mPackages) {
5211            return mSharedSystemSharedLibraryPackageName;
5212        }
5213    }
5214
5215    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5216        for (int i = userList.length - 1; i >= 0; --i) {
5217            final int userId = userList[i];
5218            // don't add instant app to the list of updates
5219            if (pkgSetting.getInstantApp(userId)) {
5220                continue;
5221            }
5222            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5223            if (changedPackages == null) {
5224                changedPackages = new SparseArray<>();
5225                mChangedPackages.put(userId, changedPackages);
5226            }
5227            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5228            if (sequenceNumbers == null) {
5229                sequenceNumbers = new HashMap<>();
5230                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5231            }
5232            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5233            if (sequenceNumber != null) {
5234                changedPackages.remove(sequenceNumber);
5235            }
5236            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5237            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5238        }
5239        mChangedPackagesSequenceNumber++;
5240    }
5241
5242    @Override
5243    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5244        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5245            return null;
5246        }
5247        synchronized (mPackages) {
5248            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5249                return null;
5250            }
5251            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5252            if (changedPackages == null) {
5253                return null;
5254            }
5255            final List<String> packageNames =
5256                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5257            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5258                final String packageName = changedPackages.get(i);
5259                if (packageName != null) {
5260                    packageNames.add(packageName);
5261                }
5262            }
5263            return packageNames.isEmpty()
5264                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5265        }
5266    }
5267
5268    @Override
5269    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5270        // allow instant applications
5271        ArrayList<FeatureInfo> res;
5272        synchronized (mAvailableFeatures) {
5273            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5274            res.addAll(mAvailableFeatures.values());
5275        }
5276        final FeatureInfo fi = new FeatureInfo();
5277        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5278                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5279        res.add(fi);
5280
5281        return new ParceledListSlice<>(res);
5282    }
5283
5284    @Override
5285    public boolean hasSystemFeature(String name, int version) {
5286        // allow instant applications
5287        synchronized (mAvailableFeatures) {
5288            final FeatureInfo feat = mAvailableFeatures.get(name);
5289            if (feat == null) {
5290                return false;
5291            } else {
5292                return feat.version >= version;
5293            }
5294        }
5295    }
5296
5297    @Override
5298    public int checkPermission(String permName, String pkgName, int userId) {
5299        return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
5300    }
5301
5302    @Override
5303    public int checkUidPermission(String permName, int uid) {
5304        synchronized (mPackages) {
5305            final String[] packageNames = getPackagesForUid(uid);
5306            final PackageParser.Package pkg = (packageNames != null && packageNames.length > 0)
5307                    ? mPackages.get(packageNames[0])
5308                    : null;
5309            return mPermissionManager.checkUidPermission(permName, pkg, uid, getCallingUid());
5310        }
5311    }
5312
5313    @Override
5314    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5315        if (UserHandle.getCallingUserId() != userId) {
5316            mContext.enforceCallingPermission(
5317                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5318                    "isPermissionRevokedByPolicy for user " + userId);
5319        }
5320
5321        if (checkPermission(permission, packageName, userId)
5322                == PackageManager.PERMISSION_GRANTED) {
5323            return false;
5324        }
5325
5326        final int callingUid = Binder.getCallingUid();
5327        if (getInstantAppPackageName(callingUid) != null) {
5328            if (!isCallerSameApp(packageName, callingUid)) {
5329                return false;
5330            }
5331        } else {
5332            if (isInstantApp(packageName, userId)) {
5333                return false;
5334            }
5335        }
5336
5337        final long identity = Binder.clearCallingIdentity();
5338        try {
5339            final int flags = getPermissionFlags(permission, packageName, userId);
5340            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5341        } finally {
5342            Binder.restoreCallingIdentity(identity);
5343        }
5344    }
5345
5346    @Override
5347    public String getPermissionControllerPackageName() {
5348        synchronized (mPackages) {
5349            return mRequiredInstallerPackage;
5350        }
5351    }
5352
5353    private boolean addDynamicPermission(PermissionInfo info, final boolean async) {
5354        return mPermissionManager.addDynamicPermission(
5355                info, async, getCallingUid(), new PermissionCallback() {
5356                    @Override
5357                    public void onPermissionChanged() {
5358                        if (!async) {
5359                            mSettings.writeLPr();
5360                        } else {
5361                            scheduleWriteSettingsLocked();
5362                        }
5363                    }
5364                });
5365    }
5366
5367    @Override
5368    public boolean addPermission(PermissionInfo info) {
5369        synchronized (mPackages) {
5370            return addDynamicPermission(info, false);
5371        }
5372    }
5373
5374    @Override
5375    public boolean addPermissionAsync(PermissionInfo info) {
5376        synchronized (mPackages) {
5377            return addDynamicPermission(info, true);
5378        }
5379    }
5380
5381    @Override
5382    public void removePermission(String permName) {
5383        mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback);
5384    }
5385
5386    @Override
5387    public void grantRuntimePermission(String packageName, String permName, final int userId) {
5388        mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
5389                getCallingUid(), userId, mPermissionCallback);
5390    }
5391
5392    @Override
5393    public void revokeRuntimePermission(String packageName, String permName, int userId) {
5394        mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
5395                getCallingUid(), userId, mPermissionCallback);
5396    }
5397
5398    @Override
5399    public void resetRuntimePermissions() {
5400        mContext.enforceCallingOrSelfPermission(
5401                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5402                "revokeRuntimePermission");
5403
5404        int callingUid = Binder.getCallingUid();
5405        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5406            mContext.enforceCallingOrSelfPermission(
5407                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5408                    "resetRuntimePermissions");
5409        }
5410
5411        synchronized (mPackages) {
5412            mPermissionManager.updateAllPermissions(
5413                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
5414                    mPermissionCallback);
5415            for (int userId : UserManagerService.getInstance().getUserIds()) {
5416                final int packageCount = mPackages.size();
5417                for (int i = 0; i < packageCount; i++) {
5418                    PackageParser.Package pkg = mPackages.valueAt(i);
5419                    if (!(pkg.mExtras instanceof PackageSetting)) {
5420                        continue;
5421                    }
5422                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5423                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5424                }
5425            }
5426        }
5427    }
5428
5429    @Override
5430    public int getPermissionFlags(String permName, String packageName, int userId) {
5431        return mPermissionManager.getPermissionFlags(
5432                permName, packageName, getCallingUid(), userId);
5433    }
5434
5435    @Override
5436    public void updatePermissionFlags(String permName, String packageName, int flagMask,
5437            int flagValues, int userId) {
5438        mPermissionManager.updatePermissionFlags(
5439                permName, packageName, flagMask, flagValues, getCallingUid(), userId,
5440                mPermissionCallback);
5441    }
5442
5443    /**
5444     * Update the permission flags for all packages and runtime permissions of a user in order
5445     * to allow device or profile owner to remove POLICY_FIXED.
5446     */
5447    @Override
5448    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5449        synchronized (mPackages) {
5450            final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5451                    flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5452                    mPermissionCallback);
5453            if (changed) {
5454                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5455            }
5456        }
5457    }
5458
5459    @Override
5460    public boolean shouldShowRequestPermissionRationale(String permissionName,
5461            String packageName, int userId) {
5462        if (UserHandle.getCallingUserId() != userId) {
5463            mContext.enforceCallingPermission(
5464                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5465                    "canShowRequestPermissionRationale for user " + userId);
5466        }
5467
5468        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5469        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5470            return false;
5471        }
5472
5473        if (checkPermission(permissionName, packageName, userId)
5474                == PackageManager.PERMISSION_GRANTED) {
5475            return false;
5476        }
5477
5478        final int flags;
5479
5480        final long identity = Binder.clearCallingIdentity();
5481        try {
5482            flags = getPermissionFlags(permissionName,
5483                    packageName, userId);
5484        } finally {
5485            Binder.restoreCallingIdentity(identity);
5486        }
5487
5488        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5489                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5490                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5491
5492        if ((flags & fixedFlags) != 0) {
5493            return false;
5494        }
5495
5496        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5497    }
5498
5499    @Override
5500    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5501        mContext.enforceCallingOrSelfPermission(
5502                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5503                "addOnPermissionsChangeListener");
5504
5505        synchronized (mPackages) {
5506            mOnPermissionChangeListeners.addListenerLocked(listener);
5507        }
5508    }
5509
5510    @Override
5511    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5512        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5513            throw new SecurityException("Instant applications don't have access to this method");
5514        }
5515        synchronized (mPackages) {
5516            mOnPermissionChangeListeners.removeListenerLocked(listener);
5517        }
5518    }
5519
5520    @Override
5521    public boolean isProtectedBroadcast(String actionName) {
5522        // allow instant applications
5523        synchronized (mProtectedBroadcasts) {
5524            if (mProtectedBroadcasts.contains(actionName)) {
5525                return true;
5526            } else if (actionName != null) {
5527                // TODO: remove these terrible hacks
5528                if (actionName.startsWith("android.net.netmon.lingerExpired")
5529                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5530                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5531                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5532                    return true;
5533                }
5534            }
5535        }
5536        return false;
5537    }
5538
5539    @Override
5540    public int checkSignatures(String pkg1, String pkg2) {
5541        synchronized (mPackages) {
5542            final PackageParser.Package p1 = mPackages.get(pkg1);
5543            final PackageParser.Package p2 = mPackages.get(pkg2);
5544            if (p1 == null || p1.mExtras == null
5545                    || p2 == null || p2.mExtras == null) {
5546                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5547            }
5548            final int callingUid = Binder.getCallingUid();
5549            final int callingUserId = UserHandle.getUserId(callingUid);
5550            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5551            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5552            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5553                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5554                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5555            }
5556            return compareSignatures(p1.mSigningDetails.signatures, p2.mSigningDetails.signatures);
5557        }
5558    }
5559
5560    @Override
5561    public int checkUidSignatures(int uid1, int uid2) {
5562        final int callingUid = Binder.getCallingUid();
5563        final int callingUserId = UserHandle.getUserId(callingUid);
5564        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5565        // Map to base uids.
5566        uid1 = UserHandle.getAppId(uid1);
5567        uid2 = UserHandle.getAppId(uid2);
5568        // reader
5569        synchronized (mPackages) {
5570            Signature[] s1;
5571            Signature[] s2;
5572            Object obj = mSettings.getUserIdLPr(uid1);
5573            if (obj != null) {
5574                if (obj instanceof SharedUserSetting) {
5575                    if (isCallerInstantApp) {
5576                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5577                    }
5578                    s1 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5579                } else if (obj instanceof PackageSetting) {
5580                    final PackageSetting ps = (PackageSetting) obj;
5581                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5582                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5583                    }
5584                    s1 = ps.signatures.mSigningDetails.signatures;
5585                } else {
5586                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5587                }
5588            } else {
5589                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5590            }
5591            obj = mSettings.getUserIdLPr(uid2);
5592            if (obj != null) {
5593                if (obj instanceof SharedUserSetting) {
5594                    if (isCallerInstantApp) {
5595                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5596                    }
5597                    s2 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5598                } else if (obj instanceof PackageSetting) {
5599                    final PackageSetting ps = (PackageSetting) obj;
5600                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5601                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5602                    }
5603                    s2 = ps.signatures.mSigningDetails.signatures;
5604                } else {
5605                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5606                }
5607            } else {
5608                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5609            }
5610            return compareSignatures(s1, s2);
5611        }
5612    }
5613
5614    @Override
5615    public boolean hasSigningCertificate(
5616            String packageName, byte[] certificate, @PackageManager.CertificateInputType int type) {
5617
5618        synchronized (mPackages) {
5619            final PackageParser.Package p = mPackages.get(packageName);
5620            if (p == null || p.mExtras == null) {
5621                return false;
5622            }
5623            final int callingUid = Binder.getCallingUid();
5624            final int callingUserId = UserHandle.getUserId(callingUid);
5625            final PackageSetting ps = (PackageSetting) p.mExtras;
5626            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5627                return false;
5628            }
5629            switch (type) {
5630                case CERT_INPUT_RAW_X509:
5631                    return p.mSigningDetails.hasCertificate(certificate);
5632                case CERT_INPUT_SHA256:
5633                    return p.mSigningDetails.hasSha256Certificate(certificate);
5634                default:
5635                    return false;
5636            }
5637        }
5638    }
5639
5640    @Override
5641    public boolean hasUidSigningCertificate(
5642            int uid, byte[] certificate, @PackageManager.CertificateInputType int type) {
5643        final int callingUid = Binder.getCallingUid();
5644        final int callingUserId = UserHandle.getUserId(callingUid);
5645        // Map to base uids.
5646        uid = UserHandle.getAppId(uid);
5647        // reader
5648        synchronized (mPackages) {
5649            final PackageParser.SigningDetails signingDetails;
5650            final Object obj = mSettings.getUserIdLPr(uid);
5651            if (obj != null) {
5652                if (obj instanceof SharedUserSetting) {
5653                    final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5654                    if (isCallerInstantApp) {
5655                        return false;
5656                    }
5657                    signingDetails = ((SharedUserSetting)obj).signatures.mSigningDetails;
5658                } else if (obj instanceof PackageSetting) {
5659                    final PackageSetting ps = (PackageSetting) obj;
5660                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5661                        return false;
5662                    }
5663                    signingDetails = ps.signatures.mSigningDetails;
5664                } else {
5665                    return false;
5666                }
5667            } else {
5668                return false;
5669            }
5670            switch (type) {
5671                case CERT_INPUT_RAW_X509:
5672                    return signingDetails.hasCertificate(certificate);
5673                case CERT_INPUT_SHA256:
5674                    return signingDetails.hasSha256Certificate(certificate);
5675                default:
5676                    return false;
5677            }
5678        }
5679    }
5680
5681    /**
5682     * This method should typically only be used when granting or revoking
5683     * permissions, since the app may immediately restart after this call.
5684     * <p>
5685     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5686     * guard your work against the app being relaunched.
5687     */
5688    private void killUid(int appId, int userId, String reason) {
5689        final long identity = Binder.clearCallingIdentity();
5690        try {
5691            IActivityManager am = ActivityManager.getService();
5692            if (am != null) {
5693                try {
5694                    am.killUid(appId, userId, reason);
5695                } catch (RemoteException e) {
5696                    /* ignore - same process */
5697                }
5698            }
5699        } finally {
5700            Binder.restoreCallingIdentity(identity);
5701        }
5702    }
5703
5704    /**
5705     * If the database version for this type of package (internal storage or
5706     * external storage) is less than the version where package signatures
5707     * were updated, return true.
5708     */
5709    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5710        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5711        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5712    }
5713
5714    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5715        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5716        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5717    }
5718
5719    @Override
5720    public List<String> getAllPackages() {
5721        final int callingUid = Binder.getCallingUid();
5722        final int callingUserId = UserHandle.getUserId(callingUid);
5723        synchronized (mPackages) {
5724            if (canViewInstantApps(callingUid, callingUserId)) {
5725                return new ArrayList<String>(mPackages.keySet());
5726            }
5727            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5728            final List<String> result = new ArrayList<>();
5729            if (instantAppPkgName != null) {
5730                // caller is an instant application; filter unexposed applications
5731                for (PackageParser.Package pkg : mPackages.values()) {
5732                    if (!pkg.visibleToInstantApps) {
5733                        continue;
5734                    }
5735                    result.add(pkg.packageName);
5736                }
5737            } else {
5738                // caller is a normal application; filter instant applications
5739                for (PackageParser.Package pkg : mPackages.values()) {
5740                    final PackageSetting ps =
5741                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5742                    if (ps != null
5743                            && ps.getInstantApp(callingUserId)
5744                            && !mInstantAppRegistry.isInstantAccessGranted(
5745                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5746                        continue;
5747                    }
5748                    result.add(pkg.packageName);
5749                }
5750            }
5751            return result;
5752        }
5753    }
5754
5755    @Override
5756    public String[] getPackagesForUid(int uid) {
5757        final int callingUid = Binder.getCallingUid();
5758        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5759        final int userId = UserHandle.getUserId(uid);
5760        uid = UserHandle.getAppId(uid);
5761        // reader
5762        synchronized (mPackages) {
5763            Object obj = mSettings.getUserIdLPr(uid);
5764            if (obj instanceof SharedUserSetting) {
5765                if (isCallerInstantApp) {
5766                    return null;
5767                }
5768                final SharedUserSetting sus = (SharedUserSetting) obj;
5769                final int N = sus.packages.size();
5770                String[] res = new String[N];
5771                final Iterator<PackageSetting> it = sus.packages.iterator();
5772                int i = 0;
5773                while (it.hasNext()) {
5774                    PackageSetting ps = it.next();
5775                    if (ps.getInstalled(userId)) {
5776                        res[i++] = ps.name;
5777                    } else {
5778                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5779                    }
5780                }
5781                return res;
5782            } else if (obj instanceof PackageSetting) {
5783                final PackageSetting ps = (PackageSetting) obj;
5784                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5785                    return new String[]{ps.name};
5786                }
5787            }
5788        }
5789        return null;
5790    }
5791
5792    @Override
5793    public String getNameForUid(int uid) {
5794        final int callingUid = Binder.getCallingUid();
5795        if (getInstantAppPackageName(callingUid) != null) {
5796            return null;
5797        }
5798        synchronized (mPackages) {
5799            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5800            if (obj instanceof SharedUserSetting) {
5801                final SharedUserSetting sus = (SharedUserSetting) obj;
5802                return sus.name + ":" + sus.userId;
5803            } else if (obj instanceof PackageSetting) {
5804                final PackageSetting ps = (PackageSetting) obj;
5805                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5806                    return null;
5807                }
5808                return ps.name;
5809            }
5810            return null;
5811        }
5812    }
5813
5814    @Override
5815    public String[] getNamesForUids(int[] uids) {
5816        if (uids == null || uids.length == 0) {
5817            return null;
5818        }
5819        final int callingUid = Binder.getCallingUid();
5820        if (getInstantAppPackageName(callingUid) != null) {
5821            return null;
5822        }
5823        final String[] names = new String[uids.length];
5824        synchronized (mPackages) {
5825            for (int i = uids.length - 1; i >= 0; i--) {
5826                final int uid = uids[i];
5827                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5828                if (obj instanceof SharedUserSetting) {
5829                    final SharedUserSetting sus = (SharedUserSetting) obj;
5830                    names[i] = "shared:" + sus.name;
5831                } else if (obj instanceof PackageSetting) {
5832                    final PackageSetting ps = (PackageSetting) obj;
5833                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5834                        names[i] = null;
5835                    } else {
5836                        names[i] = ps.name;
5837                    }
5838                } else {
5839                    names[i] = null;
5840                }
5841            }
5842        }
5843        return names;
5844    }
5845
5846    @Override
5847    public int getUidForSharedUser(String sharedUserName) {
5848        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5849            return -1;
5850        }
5851        if (sharedUserName == null) {
5852            return -1;
5853        }
5854        // reader
5855        synchronized (mPackages) {
5856            SharedUserSetting suid;
5857            try {
5858                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5859                if (suid != null) {
5860                    return suid.userId;
5861                }
5862            } catch (PackageManagerException ignore) {
5863                // can't happen, but, still need to catch it
5864            }
5865            return -1;
5866        }
5867    }
5868
5869    @Override
5870    public int getFlagsForUid(int uid) {
5871        final int callingUid = Binder.getCallingUid();
5872        if (getInstantAppPackageName(callingUid) != null) {
5873            return 0;
5874        }
5875        synchronized (mPackages) {
5876            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5877            if (obj instanceof SharedUserSetting) {
5878                final SharedUserSetting sus = (SharedUserSetting) obj;
5879                return sus.pkgFlags;
5880            } else if (obj instanceof PackageSetting) {
5881                final PackageSetting ps = (PackageSetting) obj;
5882                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5883                    return 0;
5884                }
5885                return ps.pkgFlags;
5886            }
5887        }
5888        return 0;
5889    }
5890
5891    @Override
5892    public int getPrivateFlagsForUid(int uid) {
5893        final int callingUid = Binder.getCallingUid();
5894        if (getInstantAppPackageName(callingUid) != null) {
5895            return 0;
5896        }
5897        synchronized (mPackages) {
5898            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5899            if (obj instanceof SharedUserSetting) {
5900                final SharedUserSetting sus = (SharedUserSetting) obj;
5901                return sus.pkgPrivateFlags;
5902            } else if (obj instanceof PackageSetting) {
5903                final PackageSetting ps = (PackageSetting) obj;
5904                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5905                    return 0;
5906                }
5907                return ps.pkgPrivateFlags;
5908            }
5909        }
5910        return 0;
5911    }
5912
5913    @Override
5914    public boolean isUidPrivileged(int uid) {
5915        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5916            return false;
5917        }
5918        uid = UserHandle.getAppId(uid);
5919        // reader
5920        synchronized (mPackages) {
5921            Object obj = mSettings.getUserIdLPr(uid);
5922            if (obj instanceof SharedUserSetting) {
5923                final SharedUserSetting sus = (SharedUserSetting) obj;
5924                final Iterator<PackageSetting> it = sus.packages.iterator();
5925                while (it.hasNext()) {
5926                    if (it.next().isPrivileged()) {
5927                        return true;
5928                    }
5929                }
5930            } else if (obj instanceof PackageSetting) {
5931                final PackageSetting ps = (PackageSetting) obj;
5932                return ps.isPrivileged();
5933            }
5934        }
5935        return false;
5936    }
5937
5938    @Override
5939    public String[] getAppOpPermissionPackages(String permName) {
5940        return mPermissionManager.getAppOpPermissionPackages(permName);
5941    }
5942
5943    @Override
5944    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5945            int flags, int userId) {
5946        return resolveIntentInternal(
5947                intent, resolvedType, flags, userId, false /*resolveForStart*/);
5948    }
5949
5950    /**
5951     * Normally instant apps can only be resolved when they're visible to the caller.
5952     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
5953     * since we need to allow the system to start any installed application.
5954     */
5955    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5956            int flags, int userId, boolean resolveForStart) {
5957        try {
5958            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5959
5960            if (!sUserManager.exists(userId)) return null;
5961            final int callingUid = Binder.getCallingUid();
5962            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
5963            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5964                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5965
5966            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5967            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5968                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
5969            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5970
5971            final ResolveInfo bestChoice =
5972                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5973            return bestChoice;
5974        } finally {
5975            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5976        }
5977    }
5978
5979    @Override
5980    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5981        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5982            throw new SecurityException(
5983                    "findPersistentPreferredActivity can only be run by the system");
5984        }
5985        if (!sUserManager.exists(userId)) {
5986            return null;
5987        }
5988        final int callingUid = Binder.getCallingUid();
5989        intent = updateIntentForResolve(intent);
5990        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5991        final int flags = updateFlagsForResolve(
5992                0, userId, intent, callingUid, false /*includeInstantApps*/);
5993        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5994                userId);
5995        synchronized (mPackages) {
5996            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5997                    userId);
5998        }
5999    }
6000
6001    @Override
6002    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6003            IntentFilter filter, int match, ComponentName activity) {
6004        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6005            return;
6006        }
6007        final int userId = UserHandle.getCallingUserId();
6008        if (DEBUG_PREFERRED) {
6009            Log.v(TAG, "setLastChosenActivity intent=" + intent
6010                + " resolvedType=" + resolvedType
6011                + " flags=" + flags
6012                + " filter=" + filter
6013                + " match=" + match
6014                + " activity=" + activity);
6015            filter.dump(new PrintStreamPrinter(System.out), "    ");
6016        }
6017        intent.setComponent(null);
6018        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6019                userId);
6020        // Find any earlier preferred or last chosen entries and nuke them
6021        findPreferredActivity(intent, resolvedType,
6022                flags, query, 0, false, true, false, userId);
6023        // Add the new activity as the last chosen for this filter
6024        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6025                "Setting last chosen");
6026    }
6027
6028    @Override
6029    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6030        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6031            return null;
6032        }
6033        final int userId = UserHandle.getCallingUserId();
6034        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6035        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6036                userId);
6037        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6038                false, false, false, userId);
6039    }
6040
6041    /**
6042     * Returns whether or not instant apps have been disabled remotely.
6043     */
6044    private boolean areWebInstantAppsDisabled() {
6045        return mWebInstantAppsDisabled;
6046    }
6047
6048    private boolean isInstantAppResolutionAllowed(
6049            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6050            boolean skipPackageCheck) {
6051        if (mInstantAppResolverConnection == null) {
6052            return false;
6053        }
6054        if (mInstantAppInstallerActivity == null) {
6055            return false;
6056        }
6057        if (intent.getComponent() != null) {
6058            return false;
6059        }
6060        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6061            return false;
6062        }
6063        if (!skipPackageCheck && intent.getPackage() != null) {
6064            return false;
6065        }
6066        if (!intent.isWebIntent()) {
6067            // for non web intents, we should not resolve externally if an app already exists to
6068            // handle it or if the caller didn't explicitly request it.
6069            if ((resolvedActivities != null && resolvedActivities.size() != 0)
6070                    || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) == 0) {
6071                return false;
6072            }
6073        } else {
6074            if (intent.getData() == null || TextUtils.isEmpty(intent.getData().getHost())) {
6075                return false;
6076            } else if (areWebInstantAppsDisabled()) {
6077                return false;
6078            }
6079        }
6080        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6081        // Or if there's already an ephemeral app installed that handles the action
6082        synchronized (mPackages) {
6083            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6084            for (int n = 0; n < count; n++) {
6085                final ResolveInfo info = resolvedActivities.get(n);
6086                final String packageName = info.activityInfo.packageName;
6087                final PackageSetting ps = mSettings.mPackages.get(packageName);
6088                if (ps != null) {
6089                    // only check domain verification status if the app is not a browser
6090                    if (!info.handleAllWebDataURI) {
6091                        // Try to get the status from User settings first
6092                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6093                        final int status = (int) (packedStatus >> 32);
6094                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6095                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6096                            if (DEBUG_INSTANT) {
6097                                Slog.v(TAG, "DENY instant app;"
6098                                    + " pkg: " + packageName + ", status: " + status);
6099                            }
6100                            return false;
6101                        }
6102                    }
6103                    if (ps.getInstantApp(userId)) {
6104                        if (DEBUG_INSTANT) {
6105                            Slog.v(TAG, "DENY instant app installed;"
6106                                    + " pkg: " + packageName);
6107                        }
6108                        return false;
6109                    }
6110                }
6111            }
6112        }
6113        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6114        return true;
6115    }
6116
6117    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6118            Intent origIntent, String resolvedType, String callingPackage,
6119            Bundle verificationBundle, int userId) {
6120        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6121                new InstantAppRequest(responseObj, origIntent, resolvedType,
6122                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6123        mHandler.sendMessage(msg);
6124    }
6125
6126    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6127            int flags, List<ResolveInfo> query, int userId) {
6128        if (query != null) {
6129            final int N = query.size();
6130            if (N == 1) {
6131                return query.get(0);
6132            } else if (N > 1) {
6133                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6134                // If there is more than one activity with the same priority,
6135                // then let the user decide between them.
6136                ResolveInfo r0 = query.get(0);
6137                ResolveInfo r1 = query.get(1);
6138                if (DEBUG_INTENT_MATCHING || debug) {
6139                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6140                            + r1.activityInfo.name + "=" + r1.priority);
6141                }
6142                // If the first activity has a higher priority, or a different
6143                // default, then it is always desirable to pick it.
6144                if (r0.priority != r1.priority
6145                        || r0.preferredOrder != r1.preferredOrder
6146                        || r0.isDefault != r1.isDefault) {
6147                    return query.get(0);
6148                }
6149                // If we have saved a preference for a preferred activity for
6150                // this Intent, use that.
6151                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6152                        flags, query, r0.priority, true, false, debug, userId);
6153                if (ri != null) {
6154                    return ri;
6155                }
6156                // If we have an ephemeral app, use it
6157                for (int i = 0; i < N; i++) {
6158                    ri = query.get(i);
6159                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6160                        final String packageName = ri.activityInfo.packageName;
6161                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6162                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6163                        final int status = (int)(packedStatus >> 32);
6164                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6165                            return ri;
6166                        }
6167                    }
6168                }
6169                ri = new ResolveInfo(mResolveInfo);
6170                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6171                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6172                // If all of the options come from the same package, show the application's
6173                // label and icon instead of the generic resolver's.
6174                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6175                // and then throw away the ResolveInfo itself, meaning that the caller loses
6176                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6177                // a fallback for this case; we only set the target package's resources on
6178                // the ResolveInfo, not the ActivityInfo.
6179                final String intentPackage = intent.getPackage();
6180                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6181                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6182                    ri.resolvePackageName = intentPackage;
6183                    if (userNeedsBadging(userId)) {
6184                        ri.noResourceId = true;
6185                    } else {
6186                        ri.icon = appi.icon;
6187                    }
6188                    ri.iconResourceId = appi.icon;
6189                    ri.labelRes = appi.labelRes;
6190                }
6191                ri.activityInfo.applicationInfo = new ApplicationInfo(
6192                        ri.activityInfo.applicationInfo);
6193                if (userId != 0) {
6194                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6195                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6196                }
6197                // Make sure that the resolver is displayable in car mode
6198                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6199                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6200                return ri;
6201            }
6202        }
6203        return null;
6204    }
6205
6206    /**
6207     * Return true if the given list is not empty and all of its contents have
6208     * an activityInfo with the given package name.
6209     */
6210    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6211        if (ArrayUtils.isEmpty(list)) {
6212            return false;
6213        }
6214        for (int i = 0, N = list.size(); i < N; i++) {
6215            final ResolveInfo ri = list.get(i);
6216            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6217            if (ai == null || !packageName.equals(ai.packageName)) {
6218                return false;
6219            }
6220        }
6221        return true;
6222    }
6223
6224    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6225            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6226        final int N = query.size();
6227        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6228                .get(userId);
6229        // Get the list of persistent preferred activities that handle the intent
6230        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6231        List<PersistentPreferredActivity> pprefs = ppir != null
6232                ? ppir.queryIntent(intent, resolvedType,
6233                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6234                        userId)
6235                : null;
6236        if (pprefs != null && pprefs.size() > 0) {
6237            final int M = pprefs.size();
6238            for (int i=0; i<M; i++) {
6239                final PersistentPreferredActivity ppa = pprefs.get(i);
6240                if (DEBUG_PREFERRED || debug) {
6241                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6242                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6243                            + "\n  component=" + ppa.mComponent);
6244                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6245                }
6246                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6247                        flags | MATCH_DISABLED_COMPONENTS, userId);
6248                if (DEBUG_PREFERRED || debug) {
6249                    Slog.v(TAG, "Found persistent preferred activity:");
6250                    if (ai != null) {
6251                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6252                    } else {
6253                        Slog.v(TAG, "  null");
6254                    }
6255                }
6256                if (ai == null) {
6257                    // This previously registered persistent preferred activity
6258                    // component is no longer known. Ignore it and do NOT remove it.
6259                    continue;
6260                }
6261                for (int j=0; j<N; j++) {
6262                    final ResolveInfo ri = query.get(j);
6263                    if (!ri.activityInfo.applicationInfo.packageName
6264                            .equals(ai.applicationInfo.packageName)) {
6265                        continue;
6266                    }
6267                    if (!ri.activityInfo.name.equals(ai.name)) {
6268                        continue;
6269                    }
6270                    //  Found a persistent preference that can handle the intent.
6271                    if (DEBUG_PREFERRED || debug) {
6272                        Slog.v(TAG, "Returning persistent preferred activity: " +
6273                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6274                    }
6275                    return ri;
6276                }
6277            }
6278        }
6279        return null;
6280    }
6281
6282    // TODO: handle preferred activities missing while user has amnesia
6283    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6284            List<ResolveInfo> query, int priority, boolean always,
6285            boolean removeMatches, boolean debug, int userId) {
6286        if (!sUserManager.exists(userId)) return null;
6287        final int callingUid = Binder.getCallingUid();
6288        flags = updateFlagsForResolve(
6289                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6290        intent = updateIntentForResolve(intent);
6291        // writer
6292        synchronized (mPackages) {
6293            // Try to find a matching persistent preferred activity.
6294            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6295                    debug, userId);
6296
6297            // If a persistent preferred activity matched, use it.
6298            if (pri != null) {
6299                return pri;
6300            }
6301
6302            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6303            // Get the list of preferred activities that handle the intent
6304            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6305            List<PreferredActivity> prefs = pir != null
6306                    ? pir.queryIntent(intent, resolvedType,
6307                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6308                            userId)
6309                    : null;
6310            if (prefs != null && prefs.size() > 0) {
6311                boolean changed = false;
6312                try {
6313                    // First figure out how good the original match set is.
6314                    // We will only allow preferred activities that came
6315                    // from the same match quality.
6316                    int match = 0;
6317
6318                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6319
6320                    final int N = query.size();
6321                    for (int j=0; j<N; j++) {
6322                        final ResolveInfo ri = query.get(j);
6323                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6324                                + ": 0x" + Integer.toHexString(match));
6325                        if (ri.match > match) {
6326                            match = ri.match;
6327                        }
6328                    }
6329
6330                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6331                            + Integer.toHexString(match));
6332
6333                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6334                    final int M = prefs.size();
6335                    for (int i=0; i<M; i++) {
6336                        final PreferredActivity pa = prefs.get(i);
6337                        if (DEBUG_PREFERRED || debug) {
6338                            Slog.v(TAG, "Checking PreferredActivity ds="
6339                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6340                                    + "\n  component=" + pa.mPref.mComponent);
6341                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6342                        }
6343                        if (pa.mPref.mMatch != match) {
6344                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6345                                    + Integer.toHexString(pa.mPref.mMatch));
6346                            continue;
6347                        }
6348                        // If it's not an "always" type preferred activity and that's what we're
6349                        // looking for, skip it.
6350                        if (always && !pa.mPref.mAlways) {
6351                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6352                            continue;
6353                        }
6354                        final ActivityInfo ai = getActivityInfo(
6355                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6356                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6357                                userId);
6358                        if (DEBUG_PREFERRED || debug) {
6359                            Slog.v(TAG, "Found preferred activity:");
6360                            if (ai != null) {
6361                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6362                            } else {
6363                                Slog.v(TAG, "  null");
6364                            }
6365                        }
6366                        if (ai == null) {
6367                            // This previously registered preferred activity
6368                            // component is no longer known.  Most likely an update
6369                            // to the app was installed and in the new version this
6370                            // component no longer exists.  Clean it up by removing
6371                            // it from the preferred activities list, and skip it.
6372                            Slog.w(TAG, "Removing dangling preferred activity: "
6373                                    + pa.mPref.mComponent);
6374                            pir.removeFilter(pa);
6375                            changed = true;
6376                            continue;
6377                        }
6378                        for (int j=0; j<N; j++) {
6379                            final ResolveInfo ri = query.get(j);
6380                            if (!ri.activityInfo.applicationInfo.packageName
6381                                    .equals(ai.applicationInfo.packageName)) {
6382                                continue;
6383                            }
6384                            if (!ri.activityInfo.name.equals(ai.name)) {
6385                                continue;
6386                            }
6387
6388                            if (removeMatches) {
6389                                pir.removeFilter(pa);
6390                                changed = true;
6391                                if (DEBUG_PREFERRED) {
6392                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6393                                }
6394                                break;
6395                            }
6396
6397                            // Okay we found a previously set preferred or last chosen app.
6398                            // If the result set is different from when this
6399                            // was created, and is not a subset of the preferred set, we need to
6400                            // clear it and re-ask the user their preference, if we're looking for
6401                            // an "always" type entry.
6402                            if (always && !pa.mPref.sameSet(query)) {
6403                                if (pa.mPref.isSuperset(query)) {
6404                                    // some components of the set are no longer present in
6405                                    // the query, but the preferred activity can still be reused
6406                                    if (DEBUG_PREFERRED) {
6407                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6408                                                + " still valid as only non-preferred components"
6409                                                + " were removed for " + intent + " type "
6410                                                + resolvedType);
6411                                    }
6412                                    // remove obsolete components and re-add the up-to-date filter
6413                                    PreferredActivity freshPa = new PreferredActivity(pa,
6414                                            pa.mPref.mMatch,
6415                                            pa.mPref.discardObsoleteComponents(query),
6416                                            pa.mPref.mComponent,
6417                                            pa.mPref.mAlways);
6418                                    pir.removeFilter(pa);
6419                                    pir.addFilter(freshPa);
6420                                    changed = true;
6421                                } else {
6422                                    Slog.i(TAG,
6423                                            "Result set changed, dropping preferred activity for "
6424                                                    + intent + " type " + resolvedType);
6425                                    if (DEBUG_PREFERRED) {
6426                                        Slog.v(TAG, "Removing preferred activity since set changed "
6427                                                + pa.mPref.mComponent);
6428                                    }
6429                                    pir.removeFilter(pa);
6430                                    // Re-add the filter as a "last chosen" entry (!always)
6431                                    PreferredActivity lastChosen = new PreferredActivity(
6432                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6433                                    pir.addFilter(lastChosen);
6434                                    changed = true;
6435                                    return null;
6436                                }
6437                            }
6438
6439                            // Yay! Either the set matched or we're looking for the last chosen
6440                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6441                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6442                            return ri;
6443                        }
6444                    }
6445                } finally {
6446                    if (changed) {
6447                        if (DEBUG_PREFERRED) {
6448                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6449                        }
6450                        scheduleWritePackageRestrictionsLocked(userId);
6451                    }
6452                }
6453            }
6454        }
6455        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6456        return null;
6457    }
6458
6459    /*
6460     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6461     */
6462    @Override
6463    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6464            int targetUserId) {
6465        mContext.enforceCallingOrSelfPermission(
6466                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6467        List<CrossProfileIntentFilter> matches =
6468                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6469        if (matches != null) {
6470            int size = matches.size();
6471            for (int i = 0; i < size; i++) {
6472                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6473            }
6474        }
6475        if (intent.hasWebURI()) {
6476            // cross-profile app linking works only towards the parent.
6477            final int callingUid = Binder.getCallingUid();
6478            final UserInfo parent = getProfileParent(sourceUserId);
6479            synchronized(mPackages) {
6480                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6481                        false /*includeInstantApps*/);
6482                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6483                        intent, resolvedType, flags, sourceUserId, parent.id);
6484                return xpDomainInfo != null;
6485            }
6486        }
6487        return false;
6488    }
6489
6490    private UserInfo getProfileParent(int userId) {
6491        final long identity = Binder.clearCallingIdentity();
6492        try {
6493            return sUserManager.getProfileParent(userId);
6494        } finally {
6495            Binder.restoreCallingIdentity(identity);
6496        }
6497    }
6498
6499    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6500            String resolvedType, int userId) {
6501        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6502        if (resolver != null) {
6503            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6504        }
6505        return null;
6506    }
6507
6508    @Override
6509    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6510            String resolvedType, int flags, int userId) {
6511        try {
6512            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6513
6514            return new ParceledListSlice<>(
6515                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6516        } finally {
6517            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6518        }
6519    }
6520
6521    /**
6522     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6523     * instant, returns {@code null}.
6524     */
6525    private String getInstantAppPackageName(int callingUid) {
6526        synchronized (mPackages) {
6527            // If the caller is an isolated app use the owner's uid for the lookup.
6528            if (Process.isIsolated(callingUid)) {
6529                callingUid = mIsolatedOwners.get(callingUid);
6530            }
6531            final int appId = UserHandle.getAppId(callingUid);
6532            final Object obj = mSettings.getUserIdLPr(appId);
6533            if (obj instanceof PackageSetting) {
6534                final PackageSetting ps = (PackageSetting) obj;
6535                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6536                return isInstantApp ? ps.pkg.packageName : null;
6537            }
6538        }
6539        return null;
6540    }
6541
6542    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6543            String resolvedType, int flags, int userId) {
6544        return queryIntentActivitiesInternal(
6545                intent, resolvedType, flags, Binder.getCallingUid(), userId,
6546                false /*resolveForStart*/, true /*allowDynamicSplits*/);
6547    }
6548
6549    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6550            String resolvedType, int flags, int filterCallingUid, int userId,
6551            boolean resolveForStart, boolean allowDynamicSplits) {
6552        if (!sUserManager.exists(userId)) return Collections.emptyList();
6553        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6554        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6555                false /* requireFullPermission */, false /* checkShell */,
6556                "query intent activities");
6557        final String pkgName = intent.getPackage();
6558        ComponentName comp = intent.getComponent();
6559        if (comp == null) {
6560            if (intent.getSelector() != null) {
6561                intent = intent.getSelector();
6562                comp = intent.getComponent();
6563            }
6564        }
6565
6566        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6567                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6568        if (comp != null) {
6569            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6570            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6571            if (ai != null) {
6572                // When specifying an explicit component, we prevent the activity from being
6573                // used when either 1) the calling package is normal and the activity is within
6574                // an ephemeral application or 2) the calling package is ephemeral and the
6575                // activity is not visible to ephemeral applications.
6576                final boolean matchInstantApp =
6577                        (flags & PackageManager.MATCH_INSTANT) != 0;
6578                final boolean matchVisibleToInstantAppOnly =
6579                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6580                final boolean matchExplicitlyVisibleOnly =
6581                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6582                final boolean isCallerInstantApp =
6583                        instantAppPkgName != null;
6584                final boolean isTargetSameInstantApp =
6585                        comp.getPackageName().equals(instantAppPkgName);
6586                final boolean isTargetInstantApp =
6587                        (ai.applicationInfo.privateFlags
6588                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6589                final boolean isTargetVisibleToInstantApp =
6590                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6591                final boolean isTargetExplicitlyVisibleToInstantApp =
6592                        isTargetVisibleToInstantApp
6593                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6594                final boolean isTargetHiddenFromInstantApp =
6595                        !isTargetVisibleToInstantApp
6596                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6597                final boolean blockResolution =
6598                        !isTargetSameInstantApp
6599                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6600                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6601                                        && isTargetHiddenFromInstantApp));
6602                if (!blockResolution) {
6603                    final ResolveInfo ri = new ResolveInfo();
6604                    ri.activityInfo = ai;
6605                    list.add(ri);
6606                }
6607            }
6608            return applyPostResolutionFilter(
6609                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent);
6610        }
6611
6612        // reader
6613        boolean sortResult = false;
6614        boolean addInstant = false;
6615        List<ResolveInfo> result;
6616        synchronized (mPackages) {
6617            if (pkgName == null) {
6618                List<CrossProfileIntentFilter> matchingFilters =
6619                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6620                // Check for results that need to skip the current profile.
6621                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6622                        resolvedType, flags, userId);
6623                if (xpResolveInfo != null) {
6624                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6625                    xpResult.add(xpResolveInfo);
6626                    return applyPostResolutionFilter(
6627                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6628                            allowDynamicSplits, filterCallingUid, userId, intent);
6629                }
6630
6631                // Check for results in the current profile.
6632                result = filterIfNotSystemUser(mActivities.queryIntent(
6633                        intent, resolvedType, flags, userId), userId);
6634                addInstant = isInstantAppResolutionAllowed(intent, result, userId,
6635                        false /*skipPackageCheck*/);
6636                // Check for cross profile results.
6637                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6638                xpResolveInfo = queryCrossProfileIntents(
6639                        matchingFilters, intent, resolvedType, flags, userId,
6640                        hasNonNegativePriorityResult);
6641                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6642                    boolean isVisibleToUser = filterIfNotSystemUser(
6643                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6644                    if (isVisibleToUser) {
6645                        result.add(xpResolveInfo);
6646                        sortResult = true;
6647                    }
6648                }
6649                if (intent.hasWebURI()) {
6650                    CrossProfileDomainInfo xpDomainInfo = null;
6651                    final UserInfo parent = getProfileParent(userId);
6652                    if (parent != null) {
6653                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6654                                flags, userId, parent.id);
6655                    }
6656                    if (xpDomainInfo != null) {
6657                        if (xpResolveInfo != null) {
6658                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6659                            // in the result.
6660                            result.remove(xpResolveInfo);
6661                        }
6662                        if (result.size() == 0 && !addInstant) {
6663                            // No result in current profile, but found candidate in parent user.
6664                            // And we are not going to add emphemeral app, so we can return the
6665                            // result straight away.
6666                            result.add(xpDomainInfo.resolveInfo);
6667                            return applyPostResolutionFilter(result, instantAppPkgName,
6668                                    allowDynamicSplits, filterCallingUid, userId, intent);
6669                        }
6670                    } else if (result.size() <= 1 && !addInstant) {
6671                        // No result in parent user and <= 1 result in current profile, and we
6672                        // are not going to add emphemeral app, so we can return the result without
6673                        // further processing.
6674                        return applyPostResolutionFilter(result, instantAppPkgName,
6675                                allowDynamicSplits, filterCallingUid, userId, intent);
6676                    }
6677                    // We have more than one candidate (combining results from current and parent
6678                    // profile), so we need filtering and sorting.
6679                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6680                            intent, flags, result, xpDomainInfo, userId);
6681                    sortResult = true;
6682                }
6683            } else {
6684                final PackageParser.Package pkg = mPackages.get(pkgName);
6685                result = null;
6686                if (pkg != null) {
6687                    result = filterIfNotSystemUser(
6688                            mActivities.queryIntentForPackage(
6689                                    intent, resolvedType, flags, pkg.activities, userId),
6690                            userId);
6691                }
6692                if (result == null || result.size() == 0) {
6693                    // the caller wants to resolve for a particular package; however, there
6694                    // were no installed results, so, try to find an ephemeral result
6695                    addInstant = isInstantAppResolutionAllowed(
6696                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6697                    if (result == null) {
6698                        result = new ArrayList<>();
6699                    }
6700                }
6701            }
6702        }
6703        if (addInstant) {
6704            result = maybeAddInstantAppInstaller(
6705                    result, intent, resolvedType, flags, userId, resolveForStart);
6706        }
6707        if (sortResult) {
6708            Collections.sort(result, mResolvePrioritySorter);
6709        }
6710        return applyPostResolutionFilter(
6711                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent);
6712    }
6713
6714    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6715            String resolvedType, int flags, int userId, boolean resolveForStart) {
6716        // first, check to see if we've got an instant app already installed
6717        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6718        ResolveInfo localInstantApp = null;
6719        boolean blockResolution = false;
6720        if (!alreadyResolvedLocally) {
6721            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6722                    flags
6723                        | PackageManager.GET_RESOLVED_FILTER
6724                        | PackageManager.MATCH_INSTANT
6725                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6726                    userId);
6727            for (int i = instantApps.size() - 1; i >= 0; --i) {
6728                final ResolveInfo info = instantApps.get(i);
6729                final String packageName = info.activityInfo.packageName;
6730                final PackageSetting ps = mSettings.mPackages.get(packageName);
6731                if (ps.getInstantApp(userId)) {
6732                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6733                    final int status = (int)(packedStatus >> 32);
6734                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6735                        // there's a local instant application installed, but, the user has
6736                        // chosen to never use it; skip resolution and don't acknowledge
6737                        // an instant application is even available
6738                        if (DEBUG_INSTANT) {
6739                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6740                        }
6741                        blockResolution = true;
6742                        break;
6743                    } else {
6744                        // we have a locally installed instant application; skip resolution
6745                        // but acknowledge there's an instant application available
6746                        if (DEBUG_INSTANT) {
6747                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6748                        }
6749                        localInstantApp = info;
6750                        break;
6751                    }
6752                }
6753            }
6754        }
6755        // no app installed, let's see if one's available
6756        AuxiliaryResolveInfo auxiliaryResponse = null;
6757        if (!blockResolution) {
6758            if (localInstantApp == null) {
6759                // we don't have an instant app locally, resolve externally
6760                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6761                final InstantAppRequest requestObject = new InstantAppRequest(
6762                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6763                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6764                        resolveForStart);
6765                auxiliaryResponse = InstantAppResolver.doInstantAppResolutionPhaseOne(
6766                        mInstantAppResolverConnection, requestObject);
6767                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6768            } else {
6769                // we have an instant application locally, but, we can't admit that since
6770                // callers shouldn't be able to determine prior browsing. create a dummy
6771                // auxiliary response so the downstream code behaves as if there's an
6772                // instant application available externally. when it comes time to start
6773                // the instant application, we'll do the right thing.
6774                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6775                auxiliaryResponse = new AuxiliaryResolveInfo(null /* failureActivity */,
6776                                        ai.packageName, ai.versionCode, null /* splitName */);
6777            }
6778        }
6779        if (intent.isWebIntent() && auxiliaryResponse == null) {
6780            return result;
6781        }
6782        final PackageSetting ps = mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6783        if (ps == null
6784                || ps.getUserState().get(userId) == null
6785                || !ps.getUserState().get(userId).isEnabled(mInstantAppInstallerActivity, 0)) {
6786            return result;
6787        }
6788        final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6789        ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6790                mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6791        ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6792                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6793        // add a non-generic filter
6794        ephemeralInstaller.filter = new IntentFilter();
6795        if (intent.getAction() != null) {
6796            ephemeralInstaller.filter.addAction(intent.getAction());
6797        }
6798        if (intent.getData() != null && intent.getData().getPath() != null) {
6799            ephemeralInstaller.filter.addDataPath(
6800                    intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6801        }
6802        ephemeralInstaller.isInstantAppAvailable = true;
6803        // make sure this resolver is the default
6804        ephemeralInstaller.isDefault = true;
6805        ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6806        if (DEBUG_INSTANT) {
6807            Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6808        }
6809
6810        result.add(ephemeralInstaller);
6811        return result;
6812    }
6813
6814    private static class CrossProfileDomainInfo {
6815        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6816        ResolveInfo resolveInfo;
6817        /* Best domain verification status of the activities found in the other profile */
6818        int bestDomainVerificationStatus;
6819    }
6820
6821    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6822            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6823        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6824                sourceUserId)) {
6825            return null;
6826        }
6827        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6828                resolvedType, flags, parentUserId);
6829
6830        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6831            return null;
6832        }
6833        CrossProfileDomainInfo result = null;
6834        int size = resultTargetUser.size();
6835        for (int i = 0; i < size; i++) {
6836            ResolveInfo riTargetUser = resultTargetUser.get(i);
6837            // Intent filter verification is only for filters that specify a host. So don't return
6838            // those that handle all web uris.
6839            if (riTargetUser.handleAllWebDataURI) {
6840                continue;
6841            }
6842            String packageName = riTargetUser.activityInfo.packageName;
6843            PackageSetting ps = mSettings.mPackages.get(packageName);
6844            if (ps == null) {
6845                continue;
6846            }
6847            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6848            int status = (int)(verificationState >> 32);
6849            if (result == null) {
6850                result = new CrossProfileDomainInfo();
6851                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6852                        sourceUserId, parentUserId);
6853                result.bestDomainVerificationStatus = status;
6854            } else {
6855                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6856                        result.bestDomainVerificationStatus);
6857            }
6858        }
6859        // Don't consider matches with status NEVER across profiles.
6860        if (result != null && result.bestDomainVerificationStatus
6861                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6862            return null;
6863        }
6864        return result;
6865    }
6866
6867    /**
6868     * Verification statuses are ordered from the worse to the best, except for
6869     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6870     */
6871    private int bestDomainVerificationStatus(int status1, int status2) {
6872        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6873            return status2;
6874        }
6875        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6876            return status1;
6877        }
6878        return (int) MathUtils.max(status1, status2);
6879    }
6880
6881    private boolean isUserEnabled(int userId) {
6882        long callingId = Binder.clearCallingIdentity();
6883        try {
6884            UserInfo userInfo = sUserManager.getUserInfo(userId);
6885            return userInfo != null && userInfo.isEnabled();
6886        } finally {
6887            Binder.restoreCallingIdentity(callingId);
6888        }
6889    }
6890
6891    /**
6892     * Filter out activities with systemUserOnly flag set, when current user is not System.
6893     *
6894     * @return filtered list
6895     */
6896    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6897        if (userId == UserHandle.USER_SYSTEM) {
6898            return resolveInfos;
6899        }
6900        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6901            ResolveInfo info = resolveInfos.get(i);
6902            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6903                resolveInfos.remove(i);
6904            }
6905        }
6906        return resolveInfos;
6907    }
6908
6909    /**
6910     * Filters out ephemeral activities.
6911     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6912     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6913     *
6914     * @param resolveInfos The pre-filtered list of resolved activities
6915     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6916     *          is performed.
6917     * @param intent
6918     * @return A filtered list of resolved activities.
6919     */
6920    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6921            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId,
6922            Intent intent) {
6923        final boolean blockInstant = intent.isWebIntent() && areWebInstantAppsDisabled();
6924        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6925            final ResolveInfo info = resolveInfos.get(i);
6926            // remove locally resolved instant app web results when disabled
6927            if (info.isInstantAppAvailable && blockInstant) {
6928                resolveInfos.remove(i);
6929                continue;
6930            }
6931            // allow activities that are defined in the provided package
6932            if (allowDynamicSplits
6933                    && info.activityInfo != null
6934                    && info.activityInfo.splitName != null
6935                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6936                            info.activityInfo.splitName)) {
6937                if (mInstantAppInstallerActivity == null) {
6938                    if (DEBUG_INSTALL) {
6939                        Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
6940                    }
6941                    resolveInfos.remove(i);
6942                    continue;
6943                }
6944                if (blockInstant && isInstantApp(info.activityInfo.packageName, userId)) {
6945                    resolveInfos.remove(i);
6946                    continue;
6947                }
6948                // requested activity is defined in a split that hasn't been installed yet.
6949                // add the installer to the resolve list
6950                if (DEBUG_INSTALL) {
6951                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6952                }
6953                final ResolveInfo installerInfo = new ResolveInfo(
6954                        mInstantAppInstallerInfo);
6955                final ComponentName installFailureActivity = findInstallFailureActivity(
6956                        info.activityInfo.packageName,  filterCallingUid, userId);
6957                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6958                        installFailureActivity,
6959                        info.activityInfo.packageName,
6960                        info.activityInfo.applicationInfo.versionCode,
6961                        info.activityInfo.splitName);
6962                // add a non-generic filter
6963                installerInfo.filter = new IntentFilter();
6964
6965                // This resolve info may appear in the chooser UI, so let us make it
6966                // look as the one it replaces as far as the user is concerned which
6967                // requires loading the correct label and icon for the resolve info.
6968                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6969                installerInfo.labelRes = info.resolveLabelResId();
6970                installerInfo.icon = info.resolveIconResId();
6971                installerInfo.isInstantAppAvailable = true;
6972                resolveInfos.set(i, installerInfo);
6973                continue;
6974            }
6975            // caller is a full app, don't need to apply any other filtering
6976            if (ephemeralPkgName == null) {
6977                continue;
6978            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
6979                // caller is same app; don't need to apply any other filtering
6980                continue;
6981            }
6982            // allow activities that have been explicitly exposed to ephemeral apps
6983            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6984            if (!isEphemeralApp
6985                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6986                continue;
6987            }
6988            resolveInfos.remove(i);
6989        }
6990        return resolveInfos;
6991    }
6992
6993    /**
6994     * Returns the activity component that can handle install failures.
6995     * <p>By default, the instant application installer handles failures. However, an
6996     * application may want to handle failures on its own. Applications do this by
6997     * creating an activity with an intent filter that handles the action
6998     * {@link Intent#ACTION_INSTALL_FAILURE}.
6999     */
7000    private @Nullable ComponentName findInstallFailureActivity(
7001            String packageName, int filterCallingUid, int userId) {
7002        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
7003        failureActivityIntent.setPackage(packageName);
7004        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
7005        final List<ResolveInfo> result = queryIntentActivitiesInternal(
7006                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
7007                false /*resolveForStart*/, false /*allowDynamicSplits*/);
7008        final int NR = result.size();
7009        if (NR > 0) {
7010            for (int i = 0; i < NR; i++) {
7011                final ResolveInfo info = result.get(i);
7012                if (info.activityInfo.splitName != null) {
7013                    continue;
7014                }
7015                return new ComponentName(packageName, info.activityInfo.name);
7016            }
7017        }
7018        return null;
7019    }
7020
7021    /**
7022     * @param resolveInfos list of resolve infos in descending priority order
7023     * @return if the list contains a resolve info with non-negative priority
7024     */
7025    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7026        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7027    }
7028
7029    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7030            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7031            int userId) {
7032        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7033
7034        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7035            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7036                    candidates.size());
7037        }
7038
7039        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7040        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7041        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7042        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7043        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7044        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7045
7046        synchronized (mPackages) {
7047            final int count = candidates.size();
7048            // First, try to use linked apps. Partition the candidates into four lists:
7049            // one for the final results, one for the "do not use ever", one for "undefined status"
7050            // and finally one for "browser app type".
7051            for (int n=0; n<count; n++) {
7052                ResolveInfo info = candidates.get(n);
7053                String packageName = info.activityInfo.packageName;
7054                PackageSetting ps = mSettings.mPackages.get(packageName);
7055                if (ps != null) {
7056                    // Add to the special match all list (Browser use case)
7057                    if (info.handleAllWebDataURI) {
7058                        matchAllList.add(info);
7059                        continue;
7060                    }
7061                    // Try to get the status from User settings first
7062                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7063                    int status = (int)(packedStatus >> 32);
7064                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7065                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7066                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7067                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7068                                    + " : linkgen=" + linkGeneration);
7069                        }
7070                        // Use link-enabled generation as preferredOrder, i.e.
7071                        // prefer newly-enabled over earlier-enabled.
7072                        info.preferredOrder = linkGeneration;
7073                        alwaysList.add(info);
7074                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7075                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7076                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7077                        }
7078                        neverList.add(info);
7079                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7080                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7081                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7082                        }
7083                        alwaysAskList.add(info);
7084                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7085                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7086                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7087                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7088                        }
7089                        undefinedList.add(info);
7090                    }
7091                }
7092            }
7093
7094            // We'll want to include browser possibilities in a few cases
7095            boolean includeBrowser = false;
7096
7097            // First try to add the "always" resolution(s) for the current user, if any
7098            if (alwaysList.size() > 0) {
7099                result.addAll(alwaysList);
7100            } else {
7101                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7102                result.addAll(undefinedList);
7103                // Maybe add one for the other profile.
7104                if (xpDomainInfo != null && (
7105                        xpDomainInfo.bestDomainVerificationStatus
7106                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7107                    result.add(xpDomainInfo.resolveInfo);
7108                }
7109                includeBrowser = true;
7110            }
7111
7112            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7113            // If there were 'always' entries their preferred order has been set, so we also
7114            // back that off to make the alternatives equivalent
7115            if (alwaysAskList.size() > 0) {
7116                for (ResolveInfo i : result) {
7117                    i.preferredOrder = 0;
7118                }
7119                result.addAll(alwaysAskList);
7120                includeBrowser = true;
7121            }
7122
7123            if (includeBrowser) {
7124                // Also add browsers (all of them or only the default one)
7125                if (DEBUG_DOMAIN_VERIFICATION) {
7126                    Slog.v(TAG, "   ...including browsers in candidate set");
7127                }
7128                if ((matchFlags & MATCH_ALL) != 0) {
7129                    result.addAll(matchAllList);
7130                } else {
7131                    // Browser/generic handling case.  If there's a default browser, go straight
7132                    // to that (but only if there is no other higher-priority match).
7133                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7134                    int maxMatchPrio = 0;
7135                    ResolveInfo defaultBrowserMatch = null;
7136                    final int numCandidates = matchAllList.size();
7137                    for (int n = 0; n < numCandidates; n++) {
7138                        ResolveInfo info = matchAllList.get(n);
7139                        // track the highest overall match priority...
7140                        if (info.priority > maxMatchPrio) {
7141                            maxMatchPrio = info.priority;
7142                        }
7143                        // ...and the highest-priority default browser match
7144                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7145                            if (defaultBrowserMatch == null
7146                                    || (defaultBrowserMatch.priority < info.priority)) {
7147                                if (debug) {
7148                                    Slog.v(TAG, "Considering default browser match " + info);
7149                                }
7150                                defaultBrowserMatch = info;
7151                            }
7152                        }
7153                    }
7154                    if (defaultBrowserMatch != null
7155                            && defaultBrowserMatch.priority >= maxMatchPrio
7156                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7157                    {
7158                        if (debug) {
7159                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7160                        }
7161                        result.add(defaultBrowserMatch);
7162                    } else {
7163                        result.addAll(matchAllList);
7164                    }
7165                }
7166
7167                // If there is nothing selected, add all candidates and remove the ones that the user
7168                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7169                if (result.size() == 0) {
7170                    result.addAll(candidates);
7171                    result.removeAll(neverList);
7172                }
7173            }
7174        }
7175        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7176            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7177                    result.size());
7178            for (ResolveInfo info : result) {
7179                Slog.v(TAG, "  + " + info.activityInfo);
7180            }
7181        }
7182        return result;
7183    }
7184
7185    // Returns a packed value as a long:
7186    //
7187    // high 'int'-sized word: link status: undefined/ask/never/always.
7188    // low 'int'-sized word: relative priority among 'always' results.
7189    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7190        long result = ps.getDomainVerificationStatusForUser(userId);
7191        // if none available, get the master status
7192        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7193            if (ps.getIntentFilterVerificationInfo() != null) {
7194                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7195            }
7196        }
7197        return result;
7198    }
7199
7200    private ResolveInfo querySkipCurrentProfileIntents(
7201            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7202            int flags, int sourceUserId) {
7203        if (matchingFilters != null) {
7204            int size = matchingFilters.size();
7205            for (int i = 0; i < size; i ++) {
7206                CrossProfileIntentFilter filter = matchingFilters.get(i);
7207                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7208                    // Checking if there are activities in the target user that can handle the
7209                    // intent.
7210                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7211                            resolvedType, flags, sourceUserId);
7212                    if (resolveInfo != null) {
7213                        return resolveInfo;
7214                    }
7215                }
7216            }
7217        }
7218        return null;
7219    }
7220
7221    // Return matching ResolveInfo in target user if any.
7222    private ResolveInfo queryCrossProfileIntents(
7223            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7224            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7225        if (matchingFilters != null) {
7226            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7227            // match the same intent. For performance reasons, it is better not to
7228            // run queryIntent twice for the same userId
7229            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7230            int size = matchingFilters.size();
7231            for (int i = 0; i < size; i++) {
7232                CrossProfileIntentFilter filter = matchingFilters.get(i);
7233                int targetUserId = filter.getTargetUserId();
7234                boolean skipCurrentProfile =
7235                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7236                boolean skipCurrentProfileIfNoMatchFound =
7237                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7238                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7239                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7240                    // Checking if there are activities in the target user that can handle the
7241                    // intent.
7242                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7243                            resolvedType, flags, sourceUserId);
7244                    if (resolveInfo != null) return resolveInfo;
7245                    alreadyTriedUserIds.put(targetUserId, true);
7246                }
7247            }
7248        }
7249        return null;
7250    }
7251
7252    /**
7253     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7254     * will forward the intent to the filter's target user.
7255     * Otherwise, returns null.
7256     */
7257    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7258            String resolvedType, int flags, int sourceUserId) {
7259        int targetUserId = filter.getTargetUserId();
7260        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7261                resolvedType, flags, targetUserId);
7262        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7263            // If all the matches in the target profile are suspended, return null.
7264            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7265                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7266                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7267                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7268                            targetUserId);
7269                }
7270            }
7271        }
7272        return null;
7273    }
7274
7275    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7276            int sourceUserId, int targetUserId) {
7277        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7278        long ident = Binder.clearCallingIdentity();
7279        boolean targetIsProfile;
7280        try {
7281            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7282        } finally {
7283            Binder.restoreCallingIdentity(ident);
7284        }
7285        String className;
7286        if (targetIsProfile) {
7287            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7288        } else {
7289            className = FORWARD_INTENT_TO_PARENT;
7290        }
7291        ComponentName forwardingActivityComponentName = new ComponentName(
7292                mAndroidApplication.packageName, className);
7293        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7294                sourceUserId);
7295        if (!targetIsProfile) {
7296            forwardingActivityInfo.showUserIcon = targetUserId;
7297            forwardingResolveInfo.noResourceId = true;
7298        }
7299        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7300        forwardingResolveInfo.priority = 0;
7301        forwardingResolveInfo.preferredOrder = 0;
7302        forwardingResolveInfo.match = 0;
7303        forwardingResolveInfo.isDefault = true;
7304        forwardingResolveInfo.filter = filter;
7305        forwardingResolveInfo.targetUserId = targetUserId;
7306        return forwardingResolveInfo;
7307    }
7308
7309    @Override
7310    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7311            Intent[] specifics, String[] specificTypes, Intent intent,
7312            String resolvedType, int flags, int userId) {
7313        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7314                specificTypes, intent, resolvedType, flags, userId));
7315    }
7316
7317    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7318            Intent[] specifics, String[] specificTypes, Intent intent,
7319            String resolvedType, int flags, int userId) {
7320        if (!sUserManager.exists(userId)) return Collections.emptyList();
7321        final int callingUid = Binder.getCallingUid();
7322        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7323                false /*includeInstantApps*/);
7324        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7325                false /*requireFullPermission*/, false /*checkShell*/,
7326                "query intent activity options");
7327        final String resultsAction = intent.getAction();
7328
7329        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7330                | PackageManager.GET_RESOLVED_FILTER, userId);
7331
7332        if (DEBUG_INTENT_MATCHING) {
7333            Log.v(TAG, "Query " + intent + ": " + results);
7334        }
7335
7336        int specificsPos = 0;
7337        int N;
7338
7339        // todo: note that the algorithm used here is O(N^2).  This
7340        // isn't a problem in our current environment, but if we start running
7341        // into situations where we have more than 5 or 10 matches then this
7342        // should probably be changed to something smarter...
7343
7344        // First we go through and resolve each of the specific items
7345        // that were supplied, taking care of removing any corresponding
7346        // duplicate items in the generic resolve list.
7347        if (specifics != null) {
7348            for (int i=0; i<specifics.length; i++) {
7349                final Intent sintent = specifics[i];
7350                if (sintent == null) {
7351                    continue;
7352                }
7353
7354                if (DEBUG_INTENT_MATCHING) {
7355                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7356                }
7357
7358                String action = sintent.getAction();
7359                if (resultsAction != null && resultsAction.equals(action)) {
7360                    // If this action was explicitly requested, then don't
7361                    // remove things that have it.
7362                    action = null;
7363                }
7364
7365                ResolveInfo ri = null;
7366                ActivityInfo ai = null;
7367
7368                ComponentName comp = sintent.getComponent();
7369                if (comp == null) {
7370                    ri = resolveIntent(
7371                        sintent,
7372                        specificTypes != null ? specificTypes[i] : null,
7373                            flags, userId);
7374                    if (ri == null) {
7375                        continue;
7376                    }
7377                    if (ri == mResolveInfo) {
7378                        // ACK!  Must do something better with this.
7379                    }
7380                    ai = ri.activityInfo;
7381                    comp = new ComponentName(ai.applicationInfo.packageName,
7382                            ai.name);
7383                } else {
7384                    ai = getActivityInfo(comp, flags, userId);
7385                    if (ai == null) {
7386                        continue;
7387                    }
7388                }
7389
7390                // Look for any generic query activities that are duplicates
7391                // of this specific one, and remove them from the results.
7392                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7393                N = results.size();
7394                int j;
7395                for (j=specificsPos; j<N; j++) {
7396                    ResolveInfo sri = results.get(j);
7397                    if ((sri.activityInfo.name.equals(comp.getClassName())
7398                            && sri.activityInfo.applicationInfo.packageName.equals(
7399                                    comp.getPackageName()))
7400                        || (action != null && sri.filter.matchAction(action))) {
7401                        results.remove(j);
7402                        if (DEBUG_INTENT_MATCHING) Log.v(
7403                            TAG, "Removing duplicate item from " + j
7404                            + " due to specific " + specificsPos);
7405                        if (ri == null) {
7406                            ri = sri;
7407                        }
7408                        j--;
7409                        N--;
7410                    }
7411                }
7412
7413                // Add this specific item to its proper place.
7414                if (ri == null) {
7415                    ri = new ResolveInfo();
7416                    ri.activityInfo = ai;
7417                }
7418                results.add(specificsPos, ri);
7419                ri.specificIndex = i;
7420                specificsPos++;
7421            }
7422        }
7423
7424        // Now we go through the remaining generic results and remove any
7425        // duplicate actions that are found here.
7426        N = results.size();
7427        for (int i=specificsPos; i<N-1; i++) {
7428            final ResolveInfo rii = results.get(i);
7429            if (rii.filter == null) {
7430                continue;
7431            }
7432
7433            // Iterate over all of the actions of this result's intent
7434            // filter...  typically this should be just one.
7435            final Iterator<String> it = rii.filter.actionsIterator();
7436            if (it == null) {
7437                continue;
7438            }
7439            while (it.hasNext()) {
7440                final String action = it.next();
7441                if (resultsAction != null && resultsAction.equals(action)) {
7442                    // If this action was explicitly requested, then don't
7443                    // remove things that have it.
7444                    continue;
7445                }
7446                for (int j=i+1; j<N; j++) {
7447                    final ResolveInfo rij = results.get(j);
7448                    if (rij.filter != null && rij.filter.hasAction(action)) {
7449                        results.remove(j);
7450                        if (DEBUG_INTENT_MATCHING) Log.v(
7451                            TAG, "Removing duplicate item from " + j
7452                            + " due to action " + action + " at " + i);
7453                        j--;
7454                        N--;
7455                    }
7456                }
7457            }
7458
7459            // If the caller didn't request filter information, drop it now
7460            // so we don't have to marshall/unmarshall it.
7461            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7462                rii.filter = null;
7463            }
7464        }
7465
7466        // Filter out the caller activity if so requested.
7467        if (caller != null) {
7468            N = results.size();
7469            for (int i=0; i<N; i++) {
7470                ActivityInfo ainfo = results.get(i).activityInfo;
7471                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7472                        && caller.getClassName().equals(ainfo.name)) {
7473                    results.remove(i);
7474                    break;
7475                }
7476            }
7477        }
7478
7479        // If the caller didn't request filter information,
7480        // drop them now so we don't have to
7481        // marshall/unmarshall it.
7482        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7483            N = results.size();
7484            for (int i=0; i<N; i++) {
7485                results.get(i).filter = null;
7486            }
7487        }
7488
7489        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7490        return results;
7491    }
7492
7493    @Override
7494    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7495            String resolvedType, int flags, int userId) {
7496        return new ParceledListSlice<>(
7497                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7498                        false /*allowDynamicSplits*/));
7499    }
7500
7501    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7502            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7503        if (!sUserManager.exists(userId)) return Collections.emptyList();
7504        final int callingUid = Binder.getCallingUid();
7505        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7506                false /*requireFullPermission*/, false /*checkShell*/,
7507                "query intent receivers");
7508        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7509        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7510                false /*includeInstantApps*/);
7511        ComponentName comp = intent.getComponent();
7512        if (comp == null) {
7513            if (intent.getSelector() != null) {
7514                intent = intent.getSelector();
7515                comp = intent.getComponent();
7516            }
7517        }
7518        if (comp != null) {
7519            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7520            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7521            if (ai != null) {
7522                // When specifying an explicit component, we prevent the activity from being
7523                // used when either 1) the calling package is normal and the activity is within
7524                // an instant application or 2) the calling package is ephemeral and the
7525                // activity is not visible to instant applications.
7526                final boolean matchInstantApp =
7527                        (flags & PackageManager.MATCH_INSTANT) != 0;
7528                final boolean matchVisibleToInstantAppOnly =
7529                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7530                final boolean matchExplicitlyVisibleOnly =
7531                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7532                final boolean isCallerInstantApp =
7533                        instantAppPkgName != null;
7534                final boolean isTargetSameInstantApp =
7535                        comp.getPackageName().equals(instantAppPkgName);
7536                final boolean isTargetInstantApp =
7537                        (ai.applicationInfo.privateFlags
7538                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7539                final boolean isTargetVisibleToInstantApp =
7540                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7541                final boolean isTargetExplicitlyVisibleToInstantApp =
7542                        isTargetVisibleToInstantApp
7543                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7544                final boolean isTargetHiddenFromInstantApp =
7545                        !isTargetVisibleToInstantApp
7546                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7547                final boolean blockResolution =
7548                        !isTargetSameInstantApp
7549                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7550                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7551                                        && isTargetHiddenFromInstantApp));
7552                if (!blockResolution) {
7553                    ResolveInfo ri = new ResolveInfo();
7554                    ri.activityInfo = ai;
7555                    list.add(ri);
7556                }
7557            }
7558            return applyPostResolutionFilter(
7559                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7560        }
7561
7562        // reader
7563        synchronized (mPackages) {
7564            String pkgName = intent.getPackage();
7565            if (pkgName == null) {
7566                final List<ResolveInfo> result =
7567                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7568                return applyPostResolutionFilter(
7569                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7570            }
7571            final PackageParser.Package pkg = mPackages.get(pkgName);
7572            if (pkg != null) {
7573                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7574                        intent, resolvedType, flags, pkg.receivers, userId);
7575                return applyPostResolutionFilter(
7576                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7577            }
7578            return Collections.emptyList();
7579        }
7580    }
7581
7582    @Override
7583    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7584        final int callingUid = Binder.getCallingUid();
7585        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7586    }
7587
7588    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7589            int userId, int callingUid) {
7590        if (!sUserManager.exists(userId)) return null;
7591        flags = updateFlagsForResolve(
7592                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7593        List<ResolveInfo> query = queryIntentServicesInternal(
7594                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7595        if (query != null) {
7596            if (query.size() >= 1) {
7597                // If there is more than one service with the same priority,
7598                // just arbitrarily pick the first one.
7599                return query.get(0);
7600            }
7601        }
7602        return null;
7603    }
7604
7605    @Override
7606    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7607            String resolvedType, int flags, int userId) {
7608        final int callingUid = Binder.getCallingUid();
7609        return new ParceledListSlice<>(queryIntentServicesInternal(
7610                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7611    }
7612
7613    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7614            String resolvedType, int flags, int userId, int callingUid,
7615            boolean includeInstantApps) {
7616        if (!sUserManager.exists(userId)) return Collections.emptyList();
7617        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7618                false /*requireFullPermission*/, false /*checkShell*/,
7619                "query intent receivers");
7620        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7621        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7622        ComponentName comp = intent.getComponent();
7623        if (comp == null) {
7624            if (intent.getSelector() != null) {
7625                intent = intent.getSelector();
7626                comp = intent.getComponent();
7627            }
7628        }
7629        if (comp != null) {
7630            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7631            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7632            if (si != null) {
7633                // When specifying an explicit component, we prevent the service from being
7634                // used when either 1) the service is in an instant application and the
7635                // caller is not the same instant application or 2) the calling package is
7636                // ephemeral and the activity is not visible to ephemeral applications.
7637                final boolean matchInstantApp =
7638                        (flags & PackageManager.MATCH_INSTANT) != 0;
7639                final boolean matchVisibleToInstantAppOnly =
7640                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7641                final boolean isCallerInstantApp =
7642                        instantAppPkgName != null;
7643                final boolean isTargetSameInstantApp =
7644                        comp.getPackageName().equals(instantAppPkgName);
7645                final boolean isTargetInstantApp =
7646                        (si.applicationInfo.privateFlags
7647                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7648                final boolean isTargetHiddenFromInstantApp =
7649                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7650                final boolean blockResolution =
7651                        !isTargetSameInstantApp
7652                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7653                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7654                                        && isTargetHiddenFromInstantApp));
7655                if (!blockResolution) {
7656                    final ResolveInfo ri = new ResolveInfo();
7657                    ri.serviceInfo = si;
7658                    list.add(ri);
7659                }
7660            }
7661            return list;
7662        }
7663
7664        // reader
7665        synchronized (mPackages) {
7666            String pkgName = intent.getPackage();
7667            if (pkgName == null) {
7668                return applyPostServiceResolutionFilter(
7669                        mServices.queryIntent(intent, resolvedType, flags, userId),
7670                        instantAppPkgName);
7671            }
7672            final PackageParser.Package pkg = mPackages.get(pkgName);
7673            if (pkg != null) {
7674                return applyPostServiceResolutionFilter(
7675                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7676                                userId),
7677                        instantAppPkgName);
7678            }
7679            return Collections.emptyList();
7680        }
7681    }
7682
7683    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7684            String instantAppPkgName) {
7685        if (instantAppPkgName == null) {
7686            return resolveInfos;
7687        }
7688        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7689            final ResolveInfo info = resolveInfos.get(i);
7690            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7691            // allow services that are defined in the provided package
7692            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7693                if (info.serviceInfo.splitName != null
7694                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7695                                info.serviceInfo.splitName)) {
7696                    // requested service is defined in a split that hasn't been installed yet.
7697                    // add the installer to the resolve list
7698                    if (DEBUG_INSTANT) {
7699                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7700                    }
7701                    final ResolveInfo installerInfo = new ResolveInfo(
7702                            mInstantAppInstallerInfo);
7703                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7704                            null /* installFailureActivity */,
7705                            info.serviceInfo.packageName,
7706                            info.serviceInfo.applicationInfo.versionCode,
7707                            info.serviceInfo.splitName);
7708                    // add a non-generic filter
7709                    installerInfo.filter = new IntentFilter();
7710                    // load resources from the correct package
7711                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7712                    resolveInfos.set(i, installerInfo);
7713                }
7714                continue;
7715            }
7716            // allow services that have been explicitly exposed to ephemeral apps
7717            if (!isEphemeralApp
7718                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7719                continue;
7720            }
7721            resolveInfos.remove(i);
7722        }
7723        return resolveInfos;
7724    }
7725
7726    @Override
7727    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7728            String resolvedType, int flags, int userId) {
7729        return new ParceledListSlice<>(
7730                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7731    }
7732
7733    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7734            Intent intent, String resolvedType, int flags, int userId) {
7735        if (!sUserManager.exists(userId)) return Collections.emptyList();
7736        final int callingUid = Binder.getCallingUid();
7737        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7738        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7739                false /*includeInstantApps*/);
7740        ComponentName comp = intent.getComponent();
7741        if (comp == null) {
7742            if (intent.getSelector() != null) {
7743                intent = intent.getSelector();
7744                comp = intent.getComponent();
7745            }
7746        }
7747        if (comp != null) {
7748            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7749            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7750            if (pi != null) {
7751                // When specifying an explicit component, we prevent the provider from being
7752                // used when either 1) the provider is in an instant application and the
7753                // caller is not the same instant application or 2) the calling package is an
7754                // instant application and the provider is not visible to instant applications.
7755                final boolean matchInstantApp =
7756                        (flags & PackageManager.MATCH_INSTANT) != 0;
7757                final boolean matchVisibleToInstantAppOnly =
7758                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7759                final boolean isCallerInstantApp =
7760                        instantAppPkgName != null;
7761                final boolean isTargetSameInstantApp =
7762                        comp.getPackageName().equals(instantAppPkgName);
7763                final boolean isTargetInstantApp =
7764                        (pi.applicationInfo.privateFlags
7765                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7766                final boolean isTargetHiddenFromInstantApp =
7767                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7768                final boolean blockResolution =
7769                        !isTargetSameInstantApp
7770                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7771                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7772                                        && isTargetHiddenFromInstantApp));
7773                if (!blockResolution) {
7774                    final ResolveInfo ri = new ResolveInfo();
7775                    ri.providerInfo = pi;
7776                    list.add(ri);
7777                }
7778            }
7779            return list;
7780        }
7781
7782        // reader
7783        synchronized (mPackages) {
7784            String pkgName = intent.getPackage();
7785            if (pkgName == null) {
7786                return applyPostContentProviderResolutionFilter(
7787                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7788                        instantAppPkgName);
7789            }
7790            final PackageParser.Package pkg = mPackages.get(pkgName);
7791            if (pkg != null) {
7792                return applyPostContentProviderResolutionFilter(
7793                        mProviders.queryIntentForPackage(
7794                        intent, resolvedType, flags, pkg.providers, userId),
7795                        instantAppPkgName);
7796            }
7797            return Collections.emptyList();
7798        }
7799    }
7800
7801    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7802            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7803        if (instantAppPkgName == null) {
7804            return resolveInfos;
7805        }
7806        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7807            final ResolveInfo info = resolveInfos.get(i);
7808            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7809            // allow providers that are defined in the provided package
7810            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7811                if (info.providerInfo.splitName != null
7812                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7813                                info.providerInfo.splitName)) {
7814                    // requested provider is defined in a split that hasn't been installed yet.
7815                    // add the installer to the resolve list
7816                    if (DEBUG_INSTANT) {
7817                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7818                    }
7819                    final ResolveInfo installerInfo = new ResolveInfo(
7820                            mInstantAppInstallerInfo);
7821                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7822                            null /*failureActivity*/,
7823                            info.providerInfo.packageName,
7824                            info.providerInfo.applicationInfo.versionCode,
7825                            info.providerInfo.splitName);
7826                    // add a non-generic filter
7827                    installerInfo.filter = new IntentFilter();
7828                    // load resources from the correct package
7829                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7830                    resolveInfos.set(i, installerInfo);
7831                }
7832                continue;
7833            }
7834            // allow providers that have been explicitly exposed to instant applications
7835            if (!isEphemeralApp
7836                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7837                continue;
7838            }
7839            resolveInfos.remove(i);
7840        }
7841        return resolveInfos;
7842    }
7843
7844    @Override
7845    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7846        final int callingUid = Binder.getCallingUid();
7847        if (getInstantAppPackageName(callingUid) != null) {
7848            return ParceledListSlice.emptyList();
7849        }
7850        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7851        flags = updateFlagsForPackage(flags, userId, null);
7852        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7853        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7854                true /* requireFullPermission */, false /* checkShell */,
7855                "get installed packages");
7856
7857        // writer
7858        synchronized (mPackages) {
7859            ArrayList<PackageInfo> list;
7860            if (listUninstalled) {
7861                list = new ArrayList<>(mSettings.mPackages.size());
7862                for (PackageSetting ps : mSettings.mPackages.values()) {
7863                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7864                        continue;
7865                    }
7866                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7867                        continue;
7868                    }
7869                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7870                    if (pi != null) {
7871                        list.add(pi);
7872                    }
7873                }
7874            } else {
7875                list = new ArrayList<>(mPackages.size());
7876                for (PackageParser.Package p : mPackages.values()) {
7877                    final PackageSetting ps = (PackageSetting) p.mExtras;
7878                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7879                        continue;
7880                    }
7881                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7882                        continue;
7883                    }
7884                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7885                            p.mExtras, flags, userId);
7886                    if (pi != null) {
7887                        list.add(pi);
7888                    }
7889                }
7890            }
7891
7892            return new ParceledListSlice<>(list);
7893        }
7894    }
7895
7896    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7897            String[] permissions, boolean[] tmp, int flags, int userId) {
7898        int numMatch = 0;
7899        final PermissionsState permissionsState = ps.getPermissionsState();
7900        for (int i=0; i<permissions.length; i++) {
7901            final String permission = permissions[i];
7902            if (permissionsState.hasPermission(permission, userId)) {
7903                tmp[i] = true;
7904                numMatch++;
7905            } else {
7906                tmp[i] = false;
7907            }
7908        }
7909        if (numMatch == 0) {
7910            return;
7911        }
7912        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7913
7914        // The above might return null in cases of uninstalled apps or install-state
7915        // skew across users/profiles.
7916        if (pi != null) {
7917            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7918                if (numMatch == permissions.length) {
7919                    pi.requestedPermissions = permissions;
7920                } else {
7921                    pi.requestedPermissions = new String[numMatch];
7922                    numMatch = 0;
7923                    for (int i=0; i<permissions.length; i++) {
7924                        if (tmp[i]) {
7925                            pi.requestedPermissions[numMatch] = permissions[i];
7926                            numMatch++;
7927                        }
7928                    }
7929                }
7930            }
7931            list.add(pi);
7932        }
7933    }
7934
7935    @Override
7936    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7937            String[] permissions, int flags, int userId) {
7938        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7939        flags = updateFlagsForPackage(flags, userId, permissions);
7940        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7941                true /* requireFullPermission */, false /* checkShell */,
7942                "get packages holding permissions");
7943        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7944
7945        // writer
7946        synchronized (mPackages) {
7947            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7948            boolean[] tmpBools = new boolean[permissions.length];
7949            if (listUninstalled) {
7950                for (PackageSetting ps : mSettings.mPackages.values()) {
7951                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7952                            userId);
7953                }
7954            } else {
7955                for (PackageParser.Package pkg : mPackages.values()) {
7956                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7957                    if (ps != null) {
7958                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7959                                userId);
7960                    }
7961                }
7962            }
7963
7964            return new ParceledListSlice<PackageInfo>(list);
7965        }
7966    }
7967
7968    @Override
7969    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7970        final int callingUid = Binder.getCallingUid();
7971        if (getInstantAppPackageName(callingUid) != null) {
7972            return ParceledListSlice.emptyList();
7973        }
7974        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7975        flags = updateFlagsForApplication(flags, userId, null);
7976        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7977
7978        // writer
7979        synchronized (mPackages) {
7980            ArrayList<ApplicationInfo> list;
7981            if (listUninstalled) {
7982                list = new ArrayList<>(mSettings.mPackages.size());
7983                for (PackageSetting ps : mSettings.mPackages.values()) {
7984                    ApplicationInfo ai;
7985                    int effectiveFlags = flags;
7986                    if (ps.isSystem()) {
7987                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7988                    }
7989                    if (ps.pkg != null) {
7990                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7991                            continue;
7992                        }
7993                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7994                            continue;
7995                        }
7996                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7997                                ps.readUserState(userId), userId);
7998                        if (ai != null) {
7999                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8000                        }
8001                    } else {
8002                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8003                        // and already converts to externally visible package name
8004                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8005                                callingUid, effectiveFlags, userId);
8006                    }
8007                    if (ai != null) {
8008                        list.add(ai);
8009                    }
8010                }
8011            } else {
8012                list = new ArrayList<>(mPackages.size());
8013                for (PackageParser.Package p : mPackages.values()) {
8014                    if (p.mExtras != null) {
8015                        PackageSetting ps = (PackageSetting) p.mExtras;
8016                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8017                            continue;
8018                        }
8019                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8020                            continue;
8021                        }
8022                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8023                                ps.readUserState(userId), userId);
8024                        if (ai != null) {
8025                            ai.packageName = resolveExternalPackageNameLPr(p);
8026                            list.add(ai);
8027                        }
8028                    }
8029                }
8030            }
8031
8032            return new ParceledListSlice<>(list);
8033        }
8034    }
8035
8036    @Override
8037    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8038        if (HIDE_EPHEMERAL_APIS) {
8039            return null;
8040        }
8041        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8042            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8043                    "getEphemeralApplications");
8044        }
8045        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8046                true /* requireFullPermission */, false /* checkShell */,
8047                "getEphemeralApplications");
8048        synchronized (mPackages) {
8049            List<InstantAppInfo> instantApps = mInstantAppRegistry
8050                    .getInstantAppsLPr(userId);
8051            if (instantApps != null) {
8052                return new ParceledListSlice<>(instantApps);
8053            }
8054        }
8055        return null;
8056    }
8057
8058    @Override
8059    public boolean isInstantApp(String packageName, int userId) {
8060        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8061                true /* requireFullPermission */, false /* checkShell */,
8062                "isInstantApp");
8063        if (HIDE_EPHEMERAL_APIS) {
8064            return false;
8065        }
8066
8067        synchronized (mPackages) {
8068            int callingUid = Binder.getCallingUid();
8069            if (Process.isIsolated(callingUid)) {
8070                callingUid = mIsolatedOwners.get(callingUid);
8071            }
8072            final PackageSetting ps = mSettings.mPackages.get(packageName);
8073            PackageParser.Package pkg = mPackages.get(packageName);
8074            final boolean returnAllowed =
8075                    ps != null
8076                    && (isCallerSameApp(packageName, callingUid)
8077                            || canViewInstantApps(callingUid, userId)
8078                            || mInstantAppRegistry.isInstantAccessGranted(
8079                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8080            if (returnAllowed) {
8081                return ps.getInstantApp(userId);
8082            }
8083        }
8084        return false;
8085    }
8086
8087    @Override
8088    public byte[] getInstantAppCookie(String packageName, int userId) {
8089        if (HIDE_EPHEMERAL_APIS) {
8090            return null;
8091        }
8092
8093        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8094                true /* requireFullPermission */, false /* checkShell */,
8095                "getInstantAppCookie");
8096        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8097            return null;
8098        }
8099        synchronized (mPackages) {
8100            return mInstantAppRegistry.getInstantAppCookieLPw(
8101                    packageName, userId);
8102        }
8103    }
8104
8105    @Override
8106    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8107        if (HIDE_EPHEMERAL_APIS) {
8108            return true;
8109        }
8110
8111        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8112                true /* requireFullPermission */, true /* checkShell */,
8113                "setInstantAppCookie");
8114        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8115            return false;
8116        }
8117        synchronized (mPackages) {
8118            return mInstantAppRegistry.setInstantAppCookieLPw(
8119                    packageName, cookie, userId);
8120        }
8121    }
8122
8123    @Override
8124    public Bitmap getInstantAppIcon(String packageName, int userId) {
8125        if (HIDE_EPHEMERAL_APIS) {
8126            return null;
8127        }
8128
8129        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8130            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8131                    "getInstantAppIcon");
8132        }
8133        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8134                true /* requireFullPermission */, false /* checkShell */,
8135                "getInstantAppIcon");
8136
8137        synchronized (mPackages) {
8138            return mInstantAppRegistry.getInstantAppIconLPw(
8139                    packageName, userId);
8140        }
8141    }
8142
8143    private boolean isCallerSameApp(String packageName, int uid) {
8144        PackageParser.Package pkg = mPackages.get(packageName);
8145        return pkg != null
8146                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8147    }
8148
8149    @Override
8150    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8151        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8152            return ParceledListSlice.emptyList();
8153        }
8154        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8155    }
8156
8157    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8158        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8159
8160        // reader
8161        synchronized (mPackages) {
8162            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8163            final int userId = UserHandle.getCallingUserId();
8164            while (i.hasNext()) {
8165                final PackageParser.Package p = i.next();
8166                if (p.applicationInfo == null) continue;
8167
8168                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8169                        && !p.applicationInfo.isDirectBootAware();
8170                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8171                        && p.applicationInfo.isDirectBootAware();
8172
8173                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8174                        && (!mSafeMode || isSystemApp(p))
8175                        && (matchesUnaware || matchesAware)) {
8176                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8177                    if (ps != null) {
8178                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8179                                ps.readUserState(userId), userId);
8180                        if (ai != null) {
8181                            finalList.add(ai);
8182                        }
8183                    }
8184                }
8185            }
8186        }
8187
8188        return finalList;
8189    }
8190
8191    @Override
8192    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8193        return resolveContentProviderInternal(name, flags, userId);
8194    }
8195
8196    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
8197        if (!sUserManager.exists(userId)) return null;
8198        flags = updateFlagsForComponent(flags, userId, name);
8199        final int callingUid = Binder.getCallingUid();
8200        synchronized (mPackages) {
8201            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8202            PackageSetting ps = provider != null
8203                    ? mSettings.mPackages.get(provider.owner.packageName)
8204                    : null;
8205            if (ps != null) {
8206                // provider not enabled
8207                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8208                    return null;
8209                }
8210                final ComponentName component =
8211                        new ComponentName(provider.info.packageName, provider.info.name);
8212                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8213                    return null;
8214                }
8215                return PackageParser.generateProviderInfo(
8216                        provider, flags, ps.readUserState(userId), userId);
8217            }
8218            return null;
8219        }
8220    }
8221
8222    /**
8223     * @deprecated
8224     */
8225    @Deprecated
8226    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8227        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8228            return;
8229        }
8230        // reader
8231        synchronized (mPackages) {
8232            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8233                    .entrySet().iterator();
8234            final int userId = UserHandle.getCallingUserId();
8235            while (i.hasNext()) {
8236                Map.Entry<String, PackageParser.Provider> entry = i.next();
8237                PackageParser.Provider p = entry.getValue();
8238                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8239
8240                if (ps != null && p.syncable
8241                        && (!mSafeMode || (p.info.applicationInfo.flags
8242                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8243                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8244                            ps.readUserState(userId), userId);
8245                    if (info != null) {
8246                        outNames.add(entry.getKey());
8247                        outInfo.add(info);
8248                    }
8249                }
8250            }
8251        }
8252    }
8253
8254    @Override
8255    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8256            int uid, int flags, String metaDataKey) {
8257        final int callingUid = Binder.getCallingUid();
8258        final int userId = processName != null ? UserHandle.getUserId(uid)
8259                : UserHandle.getCallingUserId();
8260        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8261        flags = updateFlagsForComponent(flags, userId, processName);
8262        ArrayList<ProviderInfo> finalList = null;
8263        // reader
8264        synchronized (mPackages) {
8265            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8266            while (i.hasNext()) {
8267                final PackageParser.Provider p = i.next();
8268                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8269                if (ps != null && p.info.authority != null
8270                        && (processName == null
8271                                || (p.info.processName.equals(processName)
8272                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8273                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8274
8275                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8276                    // parameter.
8277                    if (metaDataKey != null
8278                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8279                        continue;
8280                    }
8281                    final ComponentName component =
8282                            new ComponentName(p.info.packageName, p.info.name);
8283                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8284                        continue;
8285                    }
8286                    if (finalList == null) {
8287                        finalList = new ArrayList<ProviderInfo>(3);
8288                    }
8289                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8290                            ps.readUserState(userId), userId);
8291                    if (info != null) {
8292                        finalList.add(info);
8293                    }
8294                }
8295            }
8296        }
8297
8298        if (finalList != null) {
8299            Collections.sort(finalList, mProviderInitOrderSorter);
8300            return new ParceledListSlice<ProviderInfo>(finalList);
8301        }
8302
8303        return ParceledListSlice.emptyList();
8304    }
8305
8306    @Override
8307    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8308        // reader
8309        synchronized (mPackages) {
8310            final int callingUid = Binder.getCallingUid();
8311            final int callingUserId = UserHandle.getUserId(callingUid);
8312            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8313            if (ps == null) return null;
8314            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8315                return null;
8316            }
8317            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8318            return PackageParser.generateInstrumentationInfo(i, flags);
8319        }
8320    }
8321
8322    @Override
8323    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8324            String targetPackage, int flags) {
8325        final int callingUid = Binder.getCallingUid();
8326        final int callingUserId = UserHandle.getUserId(callingUid);
8327        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8328        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8329            return ParceledListSlice.emptyList();
8330        }
8331        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8332    }
8333
8334    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8335            int flags) {
8336        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8337
8338        // reader
8339        synchronized (mPackages) {
8340            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8341            while (i.hasNext()) {
8342                final PackageParser.Instrumentation p = i.next();
8343                if (targetPackage == null
8344                        || targetPackage.equals(p.info.targetPackage)) {
8345                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8346                            flags);
8347                    if (ii != null) {
8348                        finalList.add(ii);
8349                    }
8350                }
8351            }
8352        }
8353
8354        return finalList;
8355    }
8356
8357    private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) {
8358        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]");
8359        try {
8360            scanDirLI(scanDir, parseFlags, scanFlags, currentTime);
8361        } finally {
8362            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8363        }
8364    }
8365
8366    private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) {
8367        final File[] files = scanDir.listFiles();
8368        if (ArrayUtils.isEmpty(files)) {
8369            Log.d(TAG, "No files in app dir " + scanDir);
8370            return;
8371        }
8372
8373        if (DEBUG_PACKAGE_SCANNING) {
8374            Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags
8375                    + " flags=0x" + Integer.toHexString(parseFlags));
8376        }
8377        try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8378                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8379                mParallelPackageParserCallback)) {
8380            // Submit files for parsing in parallel
8381            int fileCount = 0;
8382            for (File file : files) {
8383                final boolean isPackage = (isApkFile(file) || file.isDirectory())
8384                        && !PackageInstallerService.isStageName(file.getName());
8385                if (!isPackage) {
8386                    // Ignore entries which are not packages
8387                    continue;
8388                }
8389                parallelPackageParser.submit(file, parseFlags);
8390                fileCount++;
8391            }
8392
8393            // Process results one by one
8394            for (; fileCount > 0; fileCount--) {
8395                ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8396                Throwable throwable = parseResult.throwable;
8397                int errorCode = PackageManager.INSTALL_SUCCEEDED;
8398
8399                if (throwable == null) {
8400                    // TODO(toddke): move lower in the scan chain
8401                    // Static shared libraries have synthetic package names
8402                    if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8403                        renameStaticSharedLibraryPackage(parseResult.pkg);
8404                    }
8405                    try {
8406                        if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8407                            scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags,
8408                                    currentTime, null);
8409                        }
8410                    } catch (PackageManagerException e) {
8411                        errorCode = e.error;
8412                        Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8413                    }
8414                } else if (throwable instanceof PackageParser.PackageParserException) {
8415                    PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8416                            throwable;
8417                    errorCode = e.error;
8418                    Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8419                } else {
8420                    throw new IllegalStateException("Unexpected exception occurred while parsing "
8421                            + parseResult.scanFile, throwable);
8422                }
8423
8424                // Delete invalid userdata apps
8425                if ((scanFlags & SCAN_AS_SYSTEM) == 0 &&
8426                        errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8427                    logCriticalInfo(Log.WARN,
8428                            "Deleting invalid package at " + parseResult.scanFile);
8429                    removeCodePathLI(parseResult.scanFile);
8430                }
8431            }
8432        }
8433    }
8434
8435    public static void reportSettingsProblem(int priority, String msg) {
8436        logCriticalInfo(priority, msg);
8437    }
8438
8439    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg,
8440            boolean forceCollect, boolean skipVerify) throws PackageManagerException {
8441        // When upgrading from pre-N MR1, verify the package time stamp using the package
8442        // directory and not the APK file.
8443        final long lastModifiedTime = mIsPreNMR1Upgrade
8444                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg);
8445        if (ps != null && !forceCollect
8446                && ps.codePathString.equals(pkg.codePath)
8447                && ps.timeStamp == lastModifiedTime
8448                && !isCompatSignatureUpdateNeeded(pkg)
8449                && !isRecoverSignatureUpdateNeeded(pkg)) {
8450            if (ps.signatures.mSigningDetails.signatures != null
8451                    && ps.signatures.mSigningDetails.signatures.length != 0
8452                    && ps.signatures.mSigningDetails.signatureSchemeVersion
8453                            != SignatureSchemeVersion.UNKNOWN) {
8454                // Optimization: reuse the existing cached signing data
8455                // if the package appears to be unchanged.
8456                pkg.mSigningDetails =
8457                        new PackageParser.SigningDetails(ps.signatures.mSigningDetails);
8458                return;
8459            }
8460
8461            Slog.w(TAG, "PackageSetting for " + ps.name
8462                    + " is missing signatures.  Collecting certs again to recover them.");
8463        } else {
8464            Slog.i(TAG, pkg.codePath + " changed; collecting certs" +
8465                    (forceCollect ? " (forced)" : ""));
8466        }
8467
8468        try {
8469            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8470            PackageParser.collectCertificates(pkg, skipVerify);
8471        } catch (PackageParserException e) {
8472            throw PackageManagerException.from(e);
8473        } finally {
8474            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8475        }
8476    }
8477
8478    /**
8479     *  Traces a package scan.
8480     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8481     */
8482    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8483            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8484        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8485        try {
8486            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8487        } finally {
8488            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8489        }
8490    }
8491
8492    /**
8493     *  Scans a package and returns the newly parsed package.
8494     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8495     */
8496    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8497            long currentTime, UserHandle user) throws PackageManagerException {
8498        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8499        PackageParser pp = new PackageParser();
8500        pp.setSeparateProcesses(mSeparateProcesses);
8501        pp.setOnlyCoreApps(mOnlyCore);
8502        pp.setDisplayMetrics(mMetrics);
8503        pp.setCallback(mPackageParserCallback);
8504
8505        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8506        final PackageParser.Package pkg;
8507        try {
8508            pkg = pp.parsePackage(scanFile, parseFlags);
8509        } catch (PackageParserException e) {
8510            throw PackageManagerException.from(e);
8511        } finally {
8512            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8513        }
8514
8515        // Static shared libraries have synthetic package names
8516        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8517            renameStaticSharedLibraryPackage(pkg);
8518        }
8519
8520        return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8521    }
8522
8523    /**
8524     *  Scans a package and returns the newly parsed package.
8525     *  @throws PackageManagerException on a parse error.
8526     */
8527    private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg,
8528            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8529            @Nullable UserHandle user)
8530                    throws PackageManagerException {
8531        // If the package has children and this is the first dive in the function
8532        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8533        // packages (parent and children) would be successfully scanned before the
8534        // actual scan since scanning mutates internal state and we want to atomically
8535        // install the package and its children.
8536        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8537            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8538                scanFlags |= SCAN_CHECK_ONLY;
8539            }
8540        } else {
8541            scanFlags &= ~SCAN_CHECK_ONLY;
8542        }
8543
8544        // Scan the parent
8545        PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags,
8546                scanFlags, currentTime, user);
8547
8548        // Scan the children
8549        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8550        for (int i = 0; i < childCount; i++) {
8551            PackageParser.Package childPackage = pkg.childPackages.get(i);
8552            addForInitLI(childPackage, parseFlags, scanFlags,
8553                    currentTime, user);
8554        }
8555
8556
8557        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8558            return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8559        }
8560
8561        return scannedPkg;
8562    }
8563
8564    /**
8565     * Returns if full apk verification can be skipped for the whole package, including the splits.
8566     */
8567    private boolean canSkipFullPackageVerification(PackageParser.Package pkg) {
8568        if (!canSkipFullApkVerification(pkg.baseCodePath)) {
8569            return false;
8570        }
8571        // TODO: Allow base and splits to be verified individually.
8572        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8573            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8574                if (!canSkipFullApkVerification(pkg.splitCodePaths[i])) {
8575                    return false;
8576                }
8577            }
8578        }
8579        return true;
8580    }
8581
8582    /**
8583     * Returns if full apk verification can be skipped, depending on current FSVerity setup and
8584     * whether the apk contains signed root hash.  Note that the signer's certificate still needs to
8585     * match one in a trusted source, and should be done separately.
8586     */
8587    private boolean canSkipFullApkVerification(String apkPath) {
8588        byte[] rootHashObserved = null;
8589        try {
8590            rootHashObserved = VerityUtils.generateFsverityRootHash(apkPath);
8591            if (rootHashObserved == null) {
8592                return false;  // APK does not contain Merkle tree root hash.
8593            }
8594            synchronized (mInstallLock) {
8595                // Returns whether the observed root hash matches what kernel has.
8596                mInstaller.assertFsverityRootHashMatches(apkPath, rootHashObserved);
8597                return true;
8598            }
8599        } catch (InstallerException | IOException | DigestException |
8600                NoSuchAlgorithmException e) {
8601            Slog.w(TAG, "Error in fsverity check. Fallback to full apk verification.", e);
8602        }
8603        return false;
8604    }
8605
8606    /**
8607     * Adds a new package to the internal data structures during platform initialization.
8608     * <p>After adding, the package is known to the system and available for querying.
8609     * <p>For packages located on the device ROM [eg. packages located in /system, /vendor,
8610     * etc...], additional checks are performed. Basic verification [such as ensuring
8611     * matching signatures, checking version codes, etc...] occurs if the package is
8612     * identical to a previously known package. If the package fails a signature check,
8613     * the version installed on /data will be removed. If the version of the new package
8614     * is less than or equal than the version on /data, it will be ignored.
8615     * <p>Regardless of the package location, the results are applied to the internal
8616     * structures and the package is made available to the rest of the system.
8617     * <p>NOTE: The return value should be removed. It's the passed in package object.
8618     */
8619    private PackageParser.Package addForInitLI(PackageParser.Package pkg,
8620            @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8621            @Nullable UserHandle user)
8622                    throws PackageManagerException {
8623        final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0;
8624        final String renamedPkgName;
8625        final PackageSetting disabledPkgSetting;
8626        final boolean isSystemPkgUpdated;
8627        final boolean pkgAlreadyExists;
8628        PackageSetting pkgSetting;
8629
8630        // NOTE: installPackageLI() has the same code to setup the package's
8631        // application info. This probably should be done lower in the call
8632        // stack [such as scanPackageOnly()]. However, we verify the application
8633        // info prior to that [in scanPackageNew()] and thus have to setup
8634        // the application info early.
8635        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8636        pkg.setApplicationInfoCodePath(pkg.codePath);
8637        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8638        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8639        pkg.setApplicationInfoResourcePath(pkg.codePath);
8640        pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
8641        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8642
8643        synchronized (mPackages) {
8644            renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8645            final String realPkgName = getRealPackageName(pkg, renamedPkgName);
8646            if (realPkgName != null) {
8647                ensurePackageRenamed(pkg, renamedPkgName);
8648            }
8649            final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
8650            final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName);
8651            pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting;
8652            pkgAlreadyExists = pkgSetting != null;
8653            final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName;
8654            disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName);
8655            isSystemPkgUpdated = disabledPkgSetting != null;
8656
8657            if (DEBUG_INSTALL && isSystemPkgUpdated) {
8658                Slog.d(TAG, "updatedPkg = " + disabledPkgSetting);
8659            }
8660
8661            final SharedUserSetting sharedUserSetting = (pkg.mSharedUserId != null)
8662                    ? mSettings.getSharedUserLPw(pkg.mSharedUserId,
8663                            0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true)
8664                    : null;
8665            if (DEBUG_PACKAGE_SCANNING
8666                    && (parseFlags & PackageParser.PARSE_CHATTY) != 0
8667                    && sharedUserSetting != null) {
8668                Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
8669                        + " (uid=" + sharedUserSetting.userId + "):"
8670                        + " packages=" + sharedUserSetting.packages);
8671            }
8672
8673            if (scanSystemPartition) {
8674                // Potentially prune child packages. If the application on the /system
8675                // partition has been updated via OTA, but, is still disabled by a
8676                // version on /data, cycle through all of its children packages and
8677                // remove children that are no longer defined.
8678                if (isSystemPkgUpdated) {
8679                    final int scannedChildCount = (pkg.childPackages != null)
8680                            ? pkg.childPackages.size() : 0;
8681                    final int disabledChildCount = disabledPkgSetting.childPackageNames != null
8682                            ? disabledPkgSetting.childPackageNames.size() : 0;
8683                    for (int i = 0; i < disabledChildCount; i++) {
8684                        String disabledChildPackageName =
8685                                disabledPkgSetting.childPackageNames.get(i);
8686                        boolean disabledPackageAvailable = false;
8687                        for (int j = 0; j < scannedChildCount; j++) {
8688                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8689                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8690                                disabledPackageAvailable = true;
8691                                break;
8692                            }
8693                        }
8694                        if (!disabledPackageAvailable) {
8695                            mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8696                        }
8697                    }
8698                    // we're updating the disabled package, so, scan it as the package setting
8699                    final ScanRequest request = new ScanRequest(pkg, sharedUserSetting,
8700                            disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */,
8701                            null /* originalPkgSetting */, null, parseFlags, scanFlags,
8702                            (pkg == mPlatformPackage), user);
8703                    applyPolicy(pkg, parseFlags, scanFlags, mPlatformPackage);
8704                    scanPackageOnlyLI(request, mFactoryTest, -1L);
8705                }
8706            }
8707        }
8708
8709        final boolean newPkgChangedPaths =
8710                pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath);
8711        final boolean newPkgVersionGreater =
8712                pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode;
8713        final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated
8714                && newPkgChangedPaths && newPkgVersionGreater;
8715        if (isSystemPkgBetter) {
8716            // The version of the application on /system is greater than the version on
8717            // /data. Switch back to the application on /system.
8718            // It's safe to assume the application on /system will correctly scan. If not,
8719            // there won't be a working copy of the application.
8720            synchronized (mPackages) {
8721                // just remove the loaded entries from package lists
8722                mPackages.remove(pkgSetting.name);
8723            }
8724
8725            logCriticalInfo(Log.WARN,
8726                    "System package updated;"
8727                    + " name: " + pkgSetting.name
8728                    + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8729                    + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8730
8731            final InstallArgs args = createInstallArgsForExisting(
8732                    packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8733                    pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8734            args.cleanUpResourcesLI();
8735            synchronized (mPackages) {
8736                mSettings.enableSystemPackageLPw(pkgSetting.name);
8737            }
8738        }
8739
8740        if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) {
8741            // The version of the application on the /system partition is less than or
8742            // equal to the version on the /data partition. Throw an exception and use
8743            // the application already installed on the /data partition.
8744            throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at "
8745                    + pkg.codePath + " ignored: updated version " + disabledPkgSetting.versionCode
8746                    + " better than this " + pkg.getLongVersionCode());
8747        }
8748
8749        // Verify certificates against what was last scanned. If it is an updated priv app, we will
8750        // force re-collecting certificate.
8751        final boolean forceCollect = PackageManagerServiceUtils.isApkVerificationForced(
8752                disabledPkgSetting);
8753        // Full APK verification can be skipped during certificate collection, only if the file is
8754        // in verified partition, or can be verified on access (when apk verity is enabled). In both
8755        // cases, only data in Signing Block is verified instead of the whole file.
8756        final boolean skipVerify = ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) ||
8757                (forceCollect && canSkipFullPackageVerification(pkg));
8758        collectCertificatesLI(pkgSetting, pkg, forceCollect, skipVerify);
8759
8760        boolean shouldHideSystemApp = false;
8761        // A new application appeared on /system, but, we already have a copy of
8762        // the application installed on /data.
8763        if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists
8764                && !pkgSetting.isSystem()) {
8765
8766            if (!pkg.mSigningDetails.checkCapability(pkgSetting.signatures.mSigningDetails,
8767                    PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)
8768                            && !pkgSetting.signatures.mSigningDetails.checkCapability(
8769                                    pkg.mSigningDetails,
8770                                    PackageParser.SigningDetails.CertCapabilities.ROLLBACK)) {
8771                logCriticalInfo(Log.WARN,
8772                        "System package signature mismatch;"
8773                        + " name: " + pkgSetting.name);
8774                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8775                        "scanPackageInternalLI")) {
8776                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8777                }
8778                pkgSetting = null;
8779            } else if (newPkgVersionGreater) {
8780                // The application on /system is newer than the application on /data.
8781                // Simply remove the application on /data [keeping application data]
8782                // and replace it with the version on /system.
8783                logCriticalInfo(Log.WARN,
8784                        "System package enabled;"
8785                        + " name: " + pkgSetting.name
8786                        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8787                        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8788                InstallArgs args = createInstallArgsForExisting(
8789                        packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8790                        pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8791                synchronized (mInstallLock) {
8792                    args.cleanUpResourcesLI();
8793                }
8794            } else {
8795                // The application on /system is older than the application on /data. Hide
8796                // the application on /system and the version on /data will be scanned later
8797                // and re-added like an update.
8798                shouldHideSystemApp = true;
8799                logCriticalInfo(Log.INFO,
8800                        "System package disabled;"
8801                        + " name: " + pkgSetting.name
8802                        + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode
8803                        + "; new: " + pkg.codePath + " @ " + pkg.codePath);
8804            }
8805        }
8806
8807        final PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags
8808                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8809
8810        if (shouldHideSystemApp) {
8811            synchronized (mPackages) {
8812                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8813            }
8814        }
8815        return scannedPkg;
8816    }
8817
8818    private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8819        // Derive the new package synthetic package name
8820        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8821                + pkg.staticSharedLibVersion);
8822    }
8823
8824    private static String fixProcessName(String defProcessName,
8825            String processName) {
8826        if (processName == null) {
8827            return defProcessName;
8828        }
8829        return processName;
8830    }
8831
8832    /**
8833     * Enforces that only the system UID or root's UID can call a method exposed
8834     * via Binder.
8835     *
8836     * @param message used as message if SecurityException is thrown
8837     * @throws SecurityException if the caller is not system or root
8838     */
8839    private static final void enforceSystemOrRoot(String message) {
8840        final int uid = Binder.getCallingUid();
8841        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8842            throw new SecurityException(message);
8843        }
8844    }
8845
8846    @Override
8847    public void performFstrimIfNeeded() {
8848        enforceSystemOrRoot("Only the system can request fstrim");
8849
8850        // Before everything else, see whether we need to fstrim.
8851        try {
8852            IStorageManager sm = PackageHelper.getStorageManager();
8853            if (sm != null) {
8854                boolean doTrim = false;
8855                final long interval = android.provider.Settings.Global.getLong(
8856                        mContext.getContentResolver(),
8857                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8858                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8859                if (interval > 0) {
8860                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8861                    if (timeSinceLast > interval) {
8862                        doTrim = true;
8863                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8864                                + "; running immediately");
8865                    }
8866                }
8867                if (doTrim) {
8868                    final boolean dexOptDialogShown;
8869                    synchronized (mPackages) {
8870                        dexOptDialogShown = mDexOptDialogShown;
8871                    }
8872                    if (!isFirstBoot() && dexOptDialogShown) {
8873                        try {
8874                            ActivityManager.getService().showBootMessage(
8875                                    mContext.getResources().getString(
8876                                            R.string.android_upgrading_fstrim), true);
8877                        } catch (RemoteException e) {
8878                        }
8879                    }
8880                    sm.runMaintenance();
8881                }
8882            } else {
8883                Slog.e(TAG, "storageManager service unavailable!");
8884            }
8885        } catch (RemoteException e) {
8886            // Can't happen; StorageManagerService is local
8887        }
8888    }
8889
8890    @Override
8891    public void updatePackagesIfNeeded() {
8892        enforceSystemOrRoot("Only the system can request package update");
8893
8894        // We need to re-extract after an OTA.
8895        boolean causeUpgrade = isUpgrade();
8896
8897        // First boot or factory reset.
8898        // Note: we also handle devices that are upgrading to N right now as if it is their
8899        //       first boot, as they do not have profile data.
8900        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8901
8902        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8903        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8904
8905        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8906            return;
8907        }
8908
8909        List<PackageParser.Package> pkgs;
8910        synchronized (mPackages) {
8911            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8912        }
8913
8914        final long startTime = System.nanoTime();
8915        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8916                    causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT,
8917                    false /* bootComplete */);
8918
8919        final int elapsedTimeSeconds =
8920                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8921
8922        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8923        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8924        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8925        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8926        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8927    }
8928
8929    /*
8930     * Return the prebuilt profile path given a package base code path.
8931     */
8932    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
8933        return pkg.baseCodePath + ".prof";
8934    }
8935
8936    /**
8937     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8938     * containing statistics about the invocation. The array consists of three elements,
8939     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8940     * and {@code numberOfPackagesFailed}.
8941     */
8942    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8943            final int compilationReason, boolean bootComplete) {
8944
8945        int numberOfPackagesVisited = 0;
8946        int numberOfPackagesOptimized = 0;
8947        int numberOfPackagesSkipped = 0;
8948        int numberOfPackagesFailed = 0;
8949        final int numberOfPackagesToDexopt = pkgs.size();
8950
8951        for (PackageParser.Package pkg : pkgs) {
8952            numberOfPackagesVisited++;
8953
8954            boolean useProfileForDexopt = false;
8955
8956            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
8957                // Copy over initial preopt profiles since we won't get any JIT samples for methods
8958                // that are already compiled.
8959                File profileFile = new File(getPrebuildProfilePath(pkg));
8960                // Copy profile if it exists.
8961                if (profileFile.exists()) {
8962                    try {
8963                        // We could also do this lazily before calling dexopt in
8964                        // PackageDexOptimizer to prevent this happening on first boot. The issue
8965                        // is that we don't have a good way to say "do this only once".
8966                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8967                                pkg.applicationInfo.uid, pkg.packageName,
8968                                ArtManager.getProfileName(null))) {
8969                            Log.e(TAG, "Installer failed to copy system profile!");
8970                        } else {
8971                            // Disabled as this causes speed-profile compilation during first boot
8972                            // even if things are already compiled.
8973                            // useProfileForDexopt = true;
8974                        }
8975                    } catch (Exception e) {
8976                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
8977                                e);
8978                    }
8979                } else {
8980                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8981                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
8982                    // minimize the number off apps being speed-profile compiled during first boot.
8983                    // The other paths will not change the filter.
8984                    if (disabledPs != null && disabledPs.pkg.isStub) {
8985                        // The package is the stub one, remove the stub suffix to get the normal
8986                        // package and APK names.
8987                        String systemProfilePath =
8988                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
8989                        profileFile = new File(systemProfilePath);
8990                        // If we have a profile for a compressed APK, copy it to the reference
8991                        // location.
8992                        // Note that copying the profile here will cause it to override the
8993                        // reference profile every OTA even though the existing reference profile
8994                        // may have more data. We can't copy during decompression since the
8995                        // directories are not set up at that point.
8996                        if (profileFile.exists()) {
8997                            try {
8998                                // We could also do this lazily before calling dexopt in
8999                                // PackageDexOptimizer to prevent this happening on first boot. The
9000                                // issue is that we don't have a good way to say "do this only
9001                                // once".
9002                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9003                                        pkg.applicationInfo.uid, pkg.packageName,
9004                                        ArtManager.getProfileName(null))) {
9005                                    Log.e(TAG, "Failed to copy system profile for stub package!");
9006                                } else {
9007                                    useProfileForDexopt = true;
9008                                }
9009                            } catch (Exception e) {
9010                                Log.e(TAG, "Failed to copy profile " +
9011                                        profileFile.getAbsolutePath() + " ", e);
9012                            }
9013                        }
9014                    }
9015                }
9016            }
9017
9018            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9019                if (DEBUG_DEXOPT) {
9020                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9021                }
9022                numberOfPackagesSkipped++;
9023                continue;
9024            }
9025
9026            if (DEBUG_DEXOPT) {
9027                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9028                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9029            }
9030
9031            if (showDialog) {
9032                try {
9033                    ActivityManager.getService().showBootMessage(
9034                            mContext.getResources().getString(R.string.android_upgrading_apk,
9035                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9036                } catch (RemoteException e) {
9037                }
9038                synchronized (mPackages) {
9039                    mDexOptDialogShown = true;
9040                }
9041            }
9042
9043            int pkgCompilationReason = compilationReason;
9044            if (useProfileForDexopt) {
9045                // Use background dexopt mode to try and use the profile. Note that this does not
9046                // guarantee usage of the profile.
9047                pkgCompilationReason = PackageManagerService.REASON_BACKGROUND_DEXOPT;
9048            }
9049
9050            // checkProfiles is false to avoid merging profiles during boot which
9051            // might interfere with background compilation (b/28612421).
9052            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9053            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9054            // trade-off worth doing to save boot time work.
9055            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9056            if (compilationReason == REASON_FIRST_BOOT) {
9057                // TODO: This doesn't cover the upgrade case, we should check for this too.
9058                dexoptFlags |= DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE;
9059            }
9060            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9061                    pkg.packageName,
9062                    pkgCompilationReason,
9063                    dexoptFlags));
9064
9065            switch (primaryDexOptStaus) {
9066                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9067                    numberOfPackagesOptimized++;
9068                    break;
9069                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9070                    numberOfPackagesSkipped++;
9071                    break;
9072                case PackageDexOptimizer.DEX_OPT_FAILED:
9073                    numberOfPackagesFailed++;
9074                    break;
9075                default:
9076                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9077                    break;
9078            }
9079        }
9080
9081        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9082                numberOfPackagesFailed };
9083    }
9084
9085    @Override
9086    public void notifyPackageUse(String packageName, int reason) {
9087        synchronized (mPackages) {
9088            final int callingUid = Binder.getCallingUid();
9089            final int callingUserId = UserHandle.getUserId(callingUid);
9090            if (getInstantAppPackageName(callingUid) != null) {
9091                if (!isCallerSameApp(packageName, callingUid)) {
9092                    return;
9093                }
9094            } else {
9095                if (isInstantApp(packageName, callingUserId)) {
9096                    return;
9097                }
9098            }
9099            notifyPackageUseLocked(packageName, reason);
9100        }
9101    }
9102
9103    @GuardedBy("mPackages")
9104    private void notifyPackageUseLocked(String packageName, int reason) {
9105        final PackageParser.Package p = mPackages.get(packageName);
9106        if (p == null) {
9107            return;
9108        }
9109        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9110    }
9111
9112    @Override
9113    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9114            List<String> classPaths, String loaderIsa) {
9115        int userId = UserHandle.getCallingUserId();
9116        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9117        if (ai == null) {
9118            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9119                + loadingPackageName + ", user=" + userId);
9120            return;
9121        }
9122        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9123    }
9124
9125    @Override
9126    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9127            IDexModuleRegisterCallback callback) {
9128        int userId = UserHandle.getCallingUserId();
9129        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9130        DexManager.RegisterDexModuleResult result;
9131        if (ai == null) {
9132            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9133                     " calling user. package=" + packageName + ", user=" + userId);
9134            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9135        } else {
9136            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9137        }
9138
9139        if (callback != null) {
9140            mHandler.post(() -> {
9141                try {
9142                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9143                } catch (RemoteException e) {
9144                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9145                }
9146            });
9147        }
9148    }
9149
9150    /**
9151     * Ask the package manager to perform a dex-opt with the given compiler filter.
9152     *
9153     * Note: exposed only for the shell command to allow moving packages explicitly to a
9154     *       definite state.
9155     */
9156    @Override
9157    public boolean performDexOptMode(String packageName,
9158            boolean checkProfiles, String targetCompilerFilter, boolean force,
9159            boolean bootComplete, String splitName) {
9160        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9161                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9162                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9163        return performDexOpt(new DexoptOptions(packageName, REASON_UNKNOWN,
9164                targetCompilerFilter, splitName, flags));
9165    }
9166
9167    /**
9168     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9169     * secondary dex files belonging to the given package.
9170     *
9171     * Note: exposed only for the shell command to allow moving packages explicitly to a
9172     *       definite state.
9173     */
9174    @Override
9175    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9176            boolean force) {
9177        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9178                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9179                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9180                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9181        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9182    }
9183
9184    /*package*/ boolean performDexOpt(DexoptOptions options) {
9185        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9186            return false;
9187        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9188            return false;
9189        }
9190
9191        if (options.isDexoptOnlySecondaryDex()) {
9192            return mDexManager.dexoptSecondaryDex(options);
9193        } else {
9194            int dexoptStatus = performDexOptWithStatus(options);
9195            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9196        }
9197    }
9198
9199    /**
9200     * Perform dexopt on the given package and return one of following result:
9201     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9202     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9203     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9204     */
9205    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9206        return performDexOptTraced(options);
9207    }
9208
9209    private int performDexOptTraced(DexoptOptions options) {
9210        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9211        try {
9212            return performDexOptInternal(options);
9213        } finally {
9214            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9215        }
9216    }
9217
9218    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9219    // if the package can now be considered up to date for the given filter.
9220    private int performDexOptInternal(DexoptOptions options) {
9221        PackageParser.Package p;
9222        synchronized (mPackages) {
9223            p = mPackages.get(options.getPackageName());
9224            if (p == null) {
9225                // Package could not be found. Report failure.
9226                return PackageDexOptimizer.DEX_OPT_FAILED;
9227            }
9228            mPackageUsage.maybeWriteAsync(mPackages);
9229            mCompilerStats.maybeWriteAsync();
9230        }
9231        long callingId = Binder.clearCallingIdentity();
9232        try {
9233            synchronized (mInstallLock) {
9234                return performDexOptInternalWithDependenciesLI(p, options);
9235            }
9236        } finally {
9237            Binder.restoreCallingIdentity(callingId);
9238        }
9239    }
9240
9241    public ArraySet<String> getOptimizablePackages() {
9242        ArraySet<String> pkgs = new ArraySet<String>();
9243        synchronized (mPackages) {
9244            for (PackageParser.Package p : mPackages.values()) {
9245                if (PackageDexOptimizer.canOptimizePackage(p)) {
9246                    pkgs.add(p.packageName);
9247                }
9248            }
9249        }
9250        return pkgs;
9251    }
9252
9253    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9254            DexoptOptions options) {
9255        // Select the dex optimizer based on the force parameter.
9256        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9257        //       allocate an object here.
9258        PackageDexOptimizer pdo = options.isForce()
9259                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9260                : mPackageDexOptimizer;
9261
9262        // Dexopt all dependencies first. Note: we ignore the return value and march on
9263        // on errors.
9264        // Note that we are going to call performDexOpt on those libraries as many times as
9265        // they are referenced in packages. When we do a batch of performDexOpt (for example
9266        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9267        // and the first package that uses the library will dexopt it. The
9268        // others will see that the compiled code for the library is up to date.
9269        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9270        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9271        if (!deps.isEmpty()) {
9272            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9273                    options.getCompilationReason(), options.getCompilerFilter(),
9274                    options.getSplitName(),
9275                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9276            for (PackageParser.Package depPackage : deps) {
9277                // TODO: Analyze and investigate if we (should) profile libraries.
9278                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9279                        getOrCreateCompilerPackageStats(depPackage),
9280                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9281            }
9282        }
9283        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9284                getOrCreateCompilerPackageStats(p),
9285                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9286    }
9287
9288    /**
9289     * Reconcile the information we have about the secondary dex files belonging to
9290     * {@code packagName} and the actual dex files. For all dex files that were
9291     * deleted, update the internal records and delete the generated oat files.
9292     */
9293    @Override
9294    public void reconcileSecondaryDexFiles(String packageName) {
9295        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9296            return;
9297        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9298            return;
9299        }
9300        mDexManager.reconcileSecondaryDexFiles(packageName);
9301    }
9302
9303    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9304    // a reference there.
9305    /*package*/ DexManager getDexManager() {
9306        return mDexManager;
9307    }
9308
9309    /**
9310     * Execute the background dexopt job immediately.
9311     */
9312    @Override
9313    public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) {
9314        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9315            return false;
9316        }
9317        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames);
9318    }
9319
9320    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9321        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9322                || p.usesStaticLibraries != null) {
9323            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9324            Set<String> collectedNames = new HashSet<>();
9325            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9326
9327            retValue.remove(p);
9328
9329            return retValue;
9330        } else {
9331            return Collections.emptyList();
9332        }
9333    }
9334
9335    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9336            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9337        if (!collectedNames.contains(p.packageName)) {
9338            collectedNames.add(p.packageName);
9339            collected.add(p);
9340
9341            if (p.usesLibraries != null) {
9342                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9343                        null, collected, collectedNames);
9344            }
9345            if (p.usesOptionalLibraries != null) {
9346                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9347                        null, collected, collectedNames);
9348            }
9349            if (p.usesStaticLibraries != null) {
9350                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9351                        p.usesStaticLibrariesVersions, collected, collectedNames);
9352            }
9353        }
9354    }
9355
9356    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions,
9357            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9358        final int libNameCount = libs.size();
9359        for (int i = 0; i < libNameCount; i++) {
9360            String libName = libs.get(i);
9361            long version = (versions != null && versions.length == libNameCount)
9362                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9363            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9364            if (libPkg != null) {
9365                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9366            }
9367        }
9368    }
9369
9370    private PackageParser.Package findSharedNonSystemLibrary(String name, long version) {
9371        synchronized (mPackages) {
9372            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9373            if (libEntry != null) {
9374                return mPackages.get(libEntry.apk);
9375            }
9376            return null;
9377        }
9378    }
9379
9380    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) {
9381        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9382        if (versionedLib == null) {
9383            return null;
9384        }
9385        return versionedLib.get(version);
9386    }
9387
9388    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9389        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9390                pkg.staticSharedLibName);
9391        if (versionedLib == null) {
9392            return null;
9393        }
9394        long previousLibVersion = -1;
9395        final int versionCount = versionedLib.size();
9396        for (int i = 0; i < versionCount; i++) {
9397            final long libVersion = versionedLib.keyAt(i);
9398            if (libVersion < pkg.staticSharedLibVersion) {
9399                previousLibVersion = Math.max(previousLibVersion, libVersion);
9400            }
9401        }
9402        if (previousLibVersion >= 0) {
9403            return versionedLib.get(previousLibVersion);
9404        }
9405        return null;
9406    }
9407
9408    public void shutdown() {
9409        mPackageUsage.writeNow(mPackages);
9410        mCompilerStats.writeNow();
9411        mDexManager.writePackageDexUsageNow();
9412    }
9413
9414    @Override
9415    public void dumpProfiles(String packageName) {
9416        PackageParser.Package pkg;
9417        synchronized (mPackages) {
9418            pkg = mPackages.get(packageName);
9419            if (pkg == null) {
9420                throw new IllegalArgumentException("Unknown package: " + packageName);
9421            }
9422        }
9423        /* Only the shell, root, or the app user should be able to dump profiles. */
9424        int callingUid = Binder.getCallingUid();
9425        if (callingUid != Process.SHELL_UID &&
9426            callingUid != Process.ROOT_UID &&
9427            callingUid != pkg.applicationInfo.uid) {
9428            throw new SecurityException("dumpProfiles");
9429        }
9430
9431        synchronized (mInstallLock) {
9432            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9433            mArtManagerService.dumpProfiles(pkg);
9434            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9435        }
9436    }
9437
9438    @Override
9439    public void forceDexOpt(String packageName) {
9440        enforceSystemOrRoot("forceDexOpt");
9441
9442        PackageParser.Package pkg;
9443        synchronized (mPackages) {
9444            pkg = mPackages.get(packageName);
9445            if (pkg == null) {
9446                throw new IllegalArgumentException("Unknown package: " + packageName);
9447            }
9448        }
9449
9450        synchronized (mInstallLock) {
9451            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9452
9453            // Whoever is calling forceDexOpt wants a compiled package.
9454            // Don't use profiles since that may cause compilation to be skipped.
9455            final int res = performDexOptInternalWithDependenciesLI(
9456                    pkg,
9457                    new DexoptOptions(packageName,
9458                            getDefaultCompilerFilter(),
9459                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9460
9461            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9462            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9463                throw new IllegalStateException("Failed to dexopt: " + res);
9464            }
9465        }
9466    }
9467
9468    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9469        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9470            Slog.w(TAG, "Unable to update from " + oldPkg.name
9471                    + " to " + newPkg.packageName
9472                    + ": old package not in system partition");
9473            return false;
9474        } else if (mPackages.get(oldPkg.name) != null) {
9475            Slog.w(TAG, "Unable to update from " + oldPkg.name
9476                    + " to " + newPkg.packageName
9477                    + ": old package still exists");
9478            return false;
9479        }
9480        return true;
9481    }
9482
9483    void removeCodePathLI(File codePath) {
9484        if (codePath.isDirectory()) {
9485            try {
9486                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9487            } catch (InstallerException e) {
9488                Slog.w(TAG, "Failed to remove code path", e);
9489            }
9490        } else {
9491            codePath.delete();
9492        }
9493    }
9494
9495    private int[] resolveUserIds(int userId) {
9496        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9497    }
9498
9499    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9500        if (pkg == null) {
9501            Slog.wtf(TAG, "Package was null!", new Throwable());
9502            return;
9503        }
9504        clearAppDataLeafLIF(pkg, userId, flags);
9505        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9506        for (int i = 0; i < childCount; i++) {
9507            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9508        }
9509
9510        clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
9511    }
9512
9513    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9514        final PackageSetting ps;
9515        synchronized (mPackages) {
9516            ps = mSettings.mPackages.get(pkg.packageName);
9517        }
9518        for (int realUserId : resolveUserIds(userId)) {
9519            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9520            try {
9521                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9522                        ceDataInode);
9523            } catch (InstallerException e) {
9524                Slog.w(TAG, String.valueOf(e));
9525            }
9526        }
9527    }
9528
9529    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9530        if (pkg == null) {
9531            Slog.wtf(TAG, "Package was null!", new Throwable());
9532            return;
9533        }
9534        destroyAppDataLeafLIF(pkg, userId, flags);
9535        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9536        for (int i = 0; i < childCount; i++) {
9537            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9538        }
9539    }
9540
9541    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9542        final PackageSetting ps;
9543        synchronized (mPackages) {
9544            ps = mSettings.mPackages.get(pkg.packageName);
9545        }
9546        for (int realUserId : resolveUserIds(userId)) {
9547            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9548            try {
9549                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9550                        ceDataInode);
9551            } catch (InstallerException e) {
9552                Slog.w(TAG, String.valueOf(e));
9553            }
9554            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9555        }
9556    }
9557
9558    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9559        if (pkg == null) {
9560            Slog.wtf(TAG, "Package was null!", new Throwable());
9561            return;
9562        }
9563        destroyAppProfilesLeafLIF(pkg);
9564        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9565        for (int i = 0; i < childCount; i++) {
9566            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9567        }
9568    }
9569
9570    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9571        try {
9572            mInstaller.destroyAppProfiles(pkg.packageName);
9573        } catch (InstallerException e) {
9574            Slog.w(TAG, String.valueOf(e));
9575        }
9576    }
9577
9578    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9579        if (pkg == null) {
9580            Slog.wtf(TAG, "Package was null!", new Throwable());
9581            return;
9582        }
9583        mArtManagerService.clearAppProfiles(pkg);
9584        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9585        for (int i = 0; i < childCount; i++) {
9586            mArtManagerService.clearAppProfiles(pkg.childPackages.get(i));
9587        }
9588    }
9589
9590    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9591            long lastUpdateTime) {
9592        // Set parent install/update time
9593        PackageSetting ps = (PackageSetting) pkg.mExtras;
9594        if (ps != null) {
9595            ps.firstInstallTime = firstInstallTime;
9596            ps.lastUpdateTime = lastUpdateTime;
9597        }
9598        // Set children install/update time
9599        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9600        for (int i = 0; i < childCount; i++) {
9601            PackageParser.Package childPkg = pkg.childPackages.get(i);
9602            ps = (PackageSetting) childPkg.mExtras;
9603            if (ps != null) {
9604                ps.firstInstallTime = firstInstallTime;
9605                ps.lastUpdateTime = lastUpdateTime;
9606            }
9607        }
9608    }
9609
9610    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9611            SharedLibraryEntry file,
9612            PackageParser.Package changingLib) {
9613        if (file.path != null) {
9614            usesLibraryFiles.add(file.path);
9615            return;
9616        }
9617        PackageParser.Package p = mPackages.get(file.apk);
9618        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9619            // If we are doing this while in the middle of updating a library apk,
9620            // then we need to make sure to use that new apk for determining the
9621            // dependencies here.  (We haven't yet finished committing the new apk
9622            // to the package manager state.)
9623            if (p == null || p.packageName.equals(changingLib.packageName)) {
9624                p = changingLib;
9625            }
9626        }
9627        if (p != null) {
9628            usesLibraryFiles.addAll(p.getAllCodePaths());
9629            if (p.usesLibraryFiles != null) {
9630                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9631            }
9632        }
9633    }
9634
9635    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9636            PackageParser.Package changingLib) throws PackageManagerException {
9637        if (pkg == null) {
9638            return;
9639        }
9640        // The collection used here must maintain the order of addition (so
9641        // that libraries are searched in the correct order) and must have no
9642        // duplicates.
9643        Set<String> usesLibraryFiles = null;
9644        if (pkg.usesLibraries != null) {
9645            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9646                    null, null, pkg.packageName, changingLib, true,
9647                    pkg.applicationInfo.targetSdkVersion, null);
9648        }
9649        if (pkg.usesStaticLibraries != null) {
9650            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9651                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9652                    pkg.packageName, changingLib, true,
9653                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9654        }
9655        if (pkg.usesOptionalLibraries != null) {
9656            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9657                    null, null, pkg.packageName, changingLib, false,
9658                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9659        }
9660        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9661            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9662        } else {
9663            pkg.usesLibraryFiles = null;
9664        }
9665    }
9666
9667    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9668            @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests,
9669            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9670            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
9671            throws PackageManagerException {
9672        final int libCount = requestedLibraries.size();
9673        for (int i = 0; i < libCount; i++) {
9674            final String libName = requestedLibraries.get(i);
9675            final long libVersion = requiredVersions != null ? requiredVersions[i]
9676                    : SharedLibraryInfo.VERSION_UNDEFINED;
9677            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9678            if (libEntry == null) {
9679                if (required) {
9680                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9681                            "Package " + packageName + " requires unavailable shared library "
9682                                    + libName + "; failing!");
9683                } else if (DEBUG_SHARED_LIBRARIES) {
9684                    Slog.i(TAG, "Package " + packageName
9685                            + " desires unavailable shared library "
9686                            + libName + "; ignoring!");
9687                }
9688            } else {
9689                if (requiredVersions != null && requiredCertDigests != null) {
9690                    if (libEntry.info.getLongVersion() != requiredVersions[i]) {
9691                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9692                            "Package " + packageName + " requires unavailable static shared"
9693                                    + " library " + libName + " version "
9694                                    + libEntry.info.getLongVersion() + "; failing!");
9695                    }
9696
9697                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9698                    if (libPkg == null) {
9699                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9700                                "Package " + packageName + " requires unavailable static shared"
9701                                        + " library; failing!");
9702                    }
9703
9704                    final String[] expectedCertDigests = requiredCertDigests[i];
9705
9706
9707                    if (expectedCertDigests.length > 1) {
9708
9709                        // For apps targeting O MR1 we require explicit enumeration of all certs.
9710                        final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
9711                                ? PackageUtils.computeSignaturesSha256Digests(
9712                                libPkg.mSigningDetails.signatures)
9713                                : PackageUtils.computeSignaturesSha256Digests(
9714                                        new Signature[]{libPkg.mSigningDetails.signatures[0]});
9715
9716                        // Take a shortcut if sizes don't match. Note that if an app doesn't
9717                        // target O we don't parse the "additional-certificate" tags similarly
9718                        // how we only consider all certs only for apps targeting O (see above).
9719                        // Therefore, the size check is safe to make.
9720                        if (expectedCertDigests.length != libCertDigests.length) {
9721                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9722                                    "Package " + packageName + " requires differently signed" +
9723                                            " static shared library; failing!");
9724                        }
9725
9726                        // Use a predictable order as signature order may vary
9727                        Arrays.sort(libCertDigests);
9728                        Arrays.sort(expectedCertDigests);
9729
9730                        final int certCount = libCertDigests.length;
9731                        for (int j = 0; j < certCount; j++) {
9732                            if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
9733                                throw new PackageManagerException(
9734                                        INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9735                                        "Package " + packageName + " requires differently signed" +
9736                                                " static shared library; failing!");
9737                            }
9738                        }
9739                    } else {
9740
9741                        // lib signing cert could have rotated beyond the one expected, check to see
9742                        // if the new one has been blessed by the old
9743                        if (!libPkg.mSigningDetails.hasSha256Certificate(
9744                                ByteStringUtils.fromHexToByteArray(expectedCertDigests[0]))) {
9745                            throw new PackageManagerException(
9746                                    INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9747                                    "Package " + packageName + " requires differently signed" +
9748                                            " static shared library; failing!");
9749                        }
9750                    }
9751                }
9752
9753                if (outUsedLibraries == null) {
9754                    // Use LinkedHashSet to preserve the order of files added to
9755                    // usesLibraryFiles while eliminating duplicates.
9756                    outUsedLibraries = new LinkedHashSet<>();
9757                }
9758                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9759            }
9760        }
9761        return outUsedLibraries;
9762    }
9763
9764    private static boolean hasString(List<String> list, List<String> which) {
9765        if (list == null) {
9766            return false;
9767        }
9768        for (int i=list.size()-1; i>=0; i--) {
9769            for (int j=which.size()-1; j>=0; j--) {
9770                if (which.get(j).equals(list.get(i))) {
9771                    return true;
9772                }
9773            }
9774        }
9775        return false;
9776    }
9777
9778    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9779            PackageParser.Package changingPkg) {
9780        ArrayList<PackageParser.Package> res = null;
9781        for (PackageParser.Package pkg : mPackages.values()) {
9782            if (changingPkg != null
9783                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9784                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9785                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9786                            changingPkg.staticSharedLibName)) {
9787                return null;
9788            }
9789            if (res == null) {
9790                res = new ArrayList<>();
9791            }
9792            res.add(pkg);
9793            try {
9794                updateSharedLibrariesLPr(pkg, changingPkg);
9795            } catch (PackageManagerException e) {
9796                // If a system app update or an app and a required lib missing we
9797                // delete the package and for updated system apps keep the data as
9798                // it is better for the user to reinstall than to be in an limbo
9799                // state. Also libs disappearing under an app should never happen
9800                // - just in case.
9801                if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) {
9802                    final int flags = pkg.isUpdatedSystemApp()
9803                            ? PackageManager.DELETE_KEEP_DATA : 0;
9804                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9805                            flags , null, true, null);
9806                }
9807                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9808            }
9809        }
9810        return res;
9811    }
9812
9813    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9814            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9815            @Nullable UserHandle user) throws PackageManagerException {
9816        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9817        // If the package has children and this is the first dive in the function
9818        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9819        // whether all packages (parent and children) would be successfully scanned
9820        // before the actual scan since scanning mutates internal state and we want
9821        // to atomically install the package and its children.
9822        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9823            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9824                scanFlags |= SCAN_CHECK_ONLY;
9825            }
9826        } else {
9827            scanFlags &= ~SCAN_CHECK_ONLY;
9828        }
9829
9830        final PackageParser.Package scannedPkg;
9831        try {
9832            // Scan the parent
9833            scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user);
9834            // Scan the children
9835            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9836            for (int i = 0; i < childCount; i++) {
9837                PackageParser.Package childPkg = pkg.childPackages.get(i);
9838                scanPackageNewLI(childPkg, parseFlags,
9839                        scanFlags, currentTime, user);
9840            }
9841        } finally {
9842            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9843        }
9844
9845        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9846            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
9847        }
9848
9849        return scannedPkg;
9850    }
9851
9852    /** The result of a package scan. */
9853    private static class ScanResult {
9854        /** Whether or not the package scan was successful */
9855        public final boolean success;
9856        /**
9857         * The final package settings. This may be the same object passed in
9858         * the {@link ScanRequest}, but, with modified values.
9859         */
9860        @Nullable public final PackageSetting pkgSetting;
9861        /** ABI code paths that have changed in the package scan */
9862        @Nullable public final List<String> changedAbiCodePath;
9863        public ScanResult(
9864                boolean success,
9865                @Nullable PackageSetting pkgSetting,
9866                @Nullable List<String> changedAbiCodePath) {
9867            this.success = success;
9868            this.pkgSetting = pkgSetting;
9869            this.changedAbiCodePath = changedAbiCodePath;
9870        }
9871    }
9872
9873    /** A package to be scanned */
9874    private static class ScanRequest {
9875        /** The parsed package */
9876        @NonNull public final PackageParser.Package pkg;
9877        /** Shared user settings, if the package has a shared user */
9878        @Nullable public final SharedUserSetting sharedUserSetting;
9879        /**
9880         * Package settings of the currently installed version.
9881         * <p><em>IMPORTANT:</em> The contents of this object may be modified
9882         * during scan.
9883         */
9884        @Nullable public final PackageSetting pkgSetting;
9885        /** A copy of the settings for the currently installed version */
9886        @Nullable public final PackageSetting oldPkgSetting;
9887        /** Package settings for the disabled version on the /system partition */
9888        @Nullable public final PackageSetting disabledPkgSetting;
9889        /** Package settings for the installed version under its original package name */
9890        @Nullable public final PackageSetting originalPkgSetting;
9891        /** The real package name of a renamed application */
9892        @Nullable public final String realPkgName;
9893        public final @ParseFlags int parseFlags;
9894        public final @ScanFlags int scanFlags;
9895        /** The user for which the package is being scanned */
9896        @Nullable public final UserHandle user;
9897        /** Whether or not the platform package is being scanned */
9898        public final boolean isPlatformPackage;
9899        public ScanRequest(
9900                @NonNull PackageParser.Package pkg,
9901                @Nullable SharedUserSetting sharedUserSetting,
9902                @Nullable PackageSetting pkgSetting,
9903                @Nullable PackageSetting disabledPkgSetting,
9904                @Nullable PackageSetting originalPkgSetting,
9905                @Nullable String realPkgName,
9906                @ParseFlags int parseFlags,
9907                @ScanFlags int scanFlags,
9908                boolean isPlatformPackage,
9909                @Nullable UserHandle user) {
9910            this.pkg = pkg;
9911            this.pkgSetting = pkgSetting;
9912            this.sharedUserSetting = sharedUserSetting;
9913            this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting);
9914            this.disabledPkgSetting = disabledPkgSetting;
9915            this.originalPkgSetting = originalPkgSetting;
9916            this.realPkgName = realPkgName;
9917            this.parseFlags = parseFlags;
9918            this.scanFlags = scanFlags;
9919            this.isPlatformPackage = isPlatformPackage;
9920            this.user = user;
9921        }
9922    }
9923
9924    /**
9925     * Returns the actual scan flags depending upon the state of the other settings.
9926     * <p>Updated system applications will not have the following flags set
9927     * by default and need to be adjusted after the fact:
9928     * <ul>
9929     * <li>{@link #SCAN_AS_SYSTEM}</li>
9930     * <li>{@link #SCAN_AS_PRIVILEGED}</li>
9931     * <li>{@link #SCAN_AS_OEM}</li>
9932     * <li>{@link #SCAN_AS_VENDOR}</li>
9933     * <li>{@link #SCAN_AS_PRODUCT}</li>
9934     * <li>{@link #SCAN_AS_INSTANT_APP}</li>
9935     * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li>
9936     * </ul>
9937     */
9938    private @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags,
9939            PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user,
9940            PackageParser.Package pkg) {
9941        if (disabledPkgSetting != null) {
9942            // updated system application, must at least have SCAN_AS_SYSTEM
9943            scanFlags |= SCAN_AS_SYSTEM;
9944            if ((disabledPkgSetting.pkgPrivateFlags
9945                    & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9946                scanFlags |= SCAN_AS_PRIVILEGED;
9947            }
9948            if ((disabledPkgSetting.pkgPrivateFlags
9949                    & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
9950                scanFlags |= SCAN_AS_OEM;
9951            }
9952            if ((disabledPkgSetting.pkgPrivateFlags
9953                    & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) {
9954                scanFlags |= SCAN_AS_VENDOR;
9955            }
9956            if ((disabledPkgSetting.pkgPrivateFlags
9957                    & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0) {
9958                scanFlags |= SCAN_AS_PRODUCT;
9959            }
9960        }
9961        if (pkgSetting != null) {
9962            final int userId = ((user == null) ? 0 : user.getIdentifier());
9963            if (pkgSetting.getInstantApp(userId)) {
9964                scanFlags |= SCAN_AS_INSTANT_APP;
9965            }
9966            if (pkgSetting.getVirtulalPreload(userId)) {
9967                scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9968            }
9969        }
9970
9971        // Scan as privileged apps that share a user with a priv-app.
9972        if (((scanFlags & SCAN_AS_PRIVILEGED) == 0) && !pkg.isPrivileged()
9973                && (pkg.mSharedUserId != null)) {
9974            SharedUserSetting sharedUserSetting = null;
9975            try {
9976                sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
9977            } catch (PackageManagerException ignore) {}
9978            if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
9979                // Exempt SharedUsers signed with the platform key.
9980                // TODO(b/72378145) Fix this exemption. Force signature apps
9981                // to whitelist their privileged permissions just like other
9982                // priv-apps.
9983                synchronized (mPackages) {
9984                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
9985                    if ((compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures,
9986                                pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) {
9987                        scanFlags |= SCAN_AS_PRIVILEGED;
9988                    }
9989                }
9990            }
9991        }
9992
9993        return scanFlags;
9994    }
9995
9996    // TODO: scanPackageNewLI() and scanPackageOnly() should be merged. But, first, commiting
9997    // the results / removing app data needs to be moved up a level to the callers of this
9998    // method. Also, we need to solve the problem of potentially creating a new shared user
9999    // setting. That can probably be done later and patch things up after the fact.
10000    @GuardedBy("mInstallLock")
10001    private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg,
10002            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
10003            @Nullable UserHandle user) throws PackageManagerException {
10004
10005        final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10006        final String realPkgName = getRealPackageName(pkg, renamedPkgName);
10007        if (realPkgName != null) {
10008            ensurePackageRenamed(pkg, renamedPkgName);
10009        }
10010        final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
10011        final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10012        final PackageSetting disabledPkgSetting =
10013                mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10014
10015        if (mTransferedPackages.contains(pkg.packageName)) {
10016            Slog.w(TAG, "Package " + pkg.packageName
10017                    + " was transferred to another, but its .apk remains");
10018        }
10019
10020        scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user, pkg);
10021        synchronized (mPackages) {
10022            applyPolicy(pkg, parseFlags, scanFlags, mPlatformPackage);
10023            assertPackageIsValid(pkg, parseFlags, scanFlags);
10024
10025            SharedUserSetting sharedUserSetting = null;
10026            if (pkg.mSharedUserId != null) {
10027                // SIDE EFFECTS; may potentially allocate a new shared user
10028                sharedUserSetting = mSettings.getSharedUserLPw(
10029                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10030                if (DEBUG_PACKAGE_SCANNING) {
10031                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10032                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
10033                                + " (uid=" + sharedUserSetting.userId + "):"
10034                                + " packages=" + sharedUserSetting.packages);
10035                }
10036            }
10037
10038            boolean scanSucceeded = false;
10039            try {
10040                final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, pkgSetting,
10041                        disabledPkgSetting, originalPkgSetting, realPkgName, parseFlags, scanFlags,
10042                        (pkg == mPlatformPackage), user);
10043                final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime);
10044                if (result.success) {
10045                    commitScanResultsLocked(request, result);
10046                }
10047                scanSucceeded = true;
10048            } finally {
10049                  if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10050                      // DELETE_DATA_ON_FAILURES is only used by frozen paths
10051                      destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10052                              StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10053                      destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10054                  }
10055            }
10056        }
10057        return pkg;
10058    }
10059
10060    /**
10061     * Commits the package scan and modifies system state.
10062     * <p><em>WARNING:</em> The method may throw an excpetion in the middle
10063     * of committing the package, leaving the system in an inconsistent state.
10064     * This needs to be fixed so, once we get to this point, no errors are
10065     * possible and the system is not left in an inconsistent state.
10066     */
10067    @GuardedBy("mPackages")
10068    private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result)
10069            throws PackageManagerException {
10070        final PackageParser.Package pkg = request.pkg;
10071        final @ParseFlags int parseFlags = request.parseFlags;
10072        final @ScanFlags int scanFlags = request.scanFlags;
10073        final PackageSetting oldPkgSetting = request.oldPkgSetting;
10074        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10075        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10076        final UserHandle user = request.user;
10077        final String realPkgName = request.realPkgName;
10078        final PackageSetting pkgSetting = result.pkgSetting;
10079        final List<String> changedAbiCodePath = result.changedAbiCodePath;
10080        final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting);
10081
10082        if (newPkgSettingCreated) {
10083            if (originalPkgSetting != null) {
10084                mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name);
10085            }
10086            // THROWS: when we can't allocate a user id. add call to check if there's
10087            // enough space to ensure we won't throw; otherwise, don't modify state
10088            mSettings.addUserToSettingLPw(pkgSetting);
10089
10090            if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) {
10091                mTransferedPackages.add(originalPkgSetting.name);
10092            }
10093        }
10094        // TODO(toddke): Consider a method specifically for modifying the Package object
10095        // post scan; or, moving this stuff out of the Package object since it has nothing
10096        // to do with the package on disk.
10097        // We need to have this here because addUserToSettingLPw() is sometimes responsible
10098        // for creating the application ID. If we did this earlier, we would be saving the
10099        // correct ID.
10100        pkg.applicationInfo.uid = pkgSetting.appId;
10101
10102        mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10103
10104        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) {
10105            mTransferedPackages.add(pkg.packageName);
10106        }
10107
10108        // THROWS: when requested libraries that can't be found. it only changes
10109        // the state of the passed in pkg object, so, move to the top of the method
10110        // and allow it to abort
10111        if ((scanFlags & SCAN_BOOTING) == 0
10112                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10113            // Check all shared libraries and map to their actual file path.
10114            // We only do this here for apps not on a system dir, because those
10115            // are the only ones that can fail an install due to this.  We
10116            // will take care of the system apps by updating all of their
10117            // library paths after the scan is done. Also during the initial
10118            // scan don't update any libs as we do this wholesale after all
10119            // apps are scanned to avoid dependency based scanning.
10120            updateSharedLibrariesLPr(pkg, null);
10121        }
10122
10123        // All versions of a static shared library are referenced with the same
10124        // package name. Internally, we use a synthetic package name to allow
10125        // multiple versions of the same shared library to be installed. So,
10126        // we need to generate the synthetic package name of the latest shared
10127        // library in order to compare signatures.
10128        PackageSetting signatureCheckPs = pkgSetting;
10129        if (pkg.applicationInfo.isStaticSharedLibrary()) {
10130            SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10131            if (libraryEntry != null) {
10132                signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10133            }
10134        }
10135
10136        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10137        if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
10138            if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
10139                // We just determined the app is signed correctly, so bring
10140                // over the latest parsed certs.
10141                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10142            } else {
10143                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10144                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10145                            "Package " + pkg.packageName + " upgrade keys do not match the "
10146                                    + "previously installed version");
10147                } else {
10148                    pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10149                    String msg = "System package " + pkg.packageName
10150                            + " signature changed; retaining data.";
10151                    reportSettingsProblem(Log.WARN, msg);
10152                }
10153            }
10154        } else {
10155            try {
10156                final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
10157                final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
10158                final boolean compatMatch = verifySignatures(signatureCheckPs, disabledPkgSetting,
10159                        pkg.mSigningDetails, compareCompat, compareRecover);
10160                // The new KeySets will be re-added later in the scanning process.
10161                if (compatMatch) {
10162                    synchronized (mPackages) {
10163                        ksms.removeAppKeySetDataLPw(pkg.packageName);
10164                    }
10165                }
10166                // We just determined the app is signed correctly, so bring
10167                // over the latest parsed certs.
10168                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10169
10170
10171                // if this is is a sharedUser, check to see if the new package is signed by a newer
10172                // signing certificate than the existing one, and if so, copy over the new details
10173                if (signatureCheckPs.sharedUser != null
10174                        && pkg.mSigningDetails.hasAncestor(
10175                                signatureCheckPs.sharedUser.signatures.mSigningDetails)) {
10176                    signatureCheckPs.sharedUser.signatures.mSigningDetails = pkg.mSigningDetails;
10177                }
10178            } catch (PackageManagerException e) {
10179                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10180                    throw e;
10181                }
10182                // The signature has changed, but this package is in the system
10183                // image...  let's recover!
10184                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10185                // However...  if this package is part of a shared user, but it
10186                // doesn't match the signature of the shared user, let's fail.
10187                // What this means is that you can't change the signatures
10188                // associated with an overall shared user, which doesn't seem all
10189                // that unreasonable.
10190                if (signatureCheckPs.sharedUser != null) {
10191                    if (compareSignatures(
10192                            signatureCheckPs.sharedUser.signatures.mSigningDetails.signatures,
10193                            pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH) {
10194                        throw new PackageManagerException(
10195                                INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10196                                "Signature mismatch for shared user: "
10197                                        + pkgSetting.sharedUser);
10198                    }
10199                }
10200                // File a report about this.
10201                String msg = "System package " + pkg.packageName
10202                        + " signature changed; retaining data.";
10203                reportSettingsProblem(Log.WARN, msg);
10204            } catch (IllegalArgumentException e) {
10205
10206                // should never happen: certs matched when checking, but not when comparing
10207                // old to new for sharedUser
10208                throw new PackageManagerException(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10209                        "Signing certificates comparison made on incomparable signing details"
10210                        + " but somehow passed verifySignatures!");
10211            }
10212        }
10213
10214        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10215            // This package wants to adopt ownership of permissions from
10216            // another package.
10217            for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10218                final String origName = pkg.mAdoptPermissions.get(i);
10219                final PackageSetting orig = mSettings.getPackageLPr(origName);
10220                if (orig != null) {
10221                    if (verifyPackageUpdateLPr(orig, pkg)) {
10222                        Slog.i(TAG, "Adopting permissions from " + origName + " to "
10223                                + pkg.packageName);
10224                        mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
10225                    }
10226                }
10227            }
10228        }
10229
10230        if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
10231            for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
10232                final String codePathString = changedAbiCodePath.get(i);
10233                try {
10234                    mInstaller.rmdex(codePathString,
10235                            getDexCodeInstructionSet(getPreferredInstructionSet()));
10236                } catch (InstallerException ignored) {
10237                }
10238            }
10239        }
10240
10241        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10242            if (oldPkgSetting != null) {
10243                synchronized (mPackages) {
10244                    mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting);
10245                }
10246            }
10247        } else {
10248            final int userId = user == null ? 0 : user.getIdentifier();
10249            // Modify state for the given package setting
10250            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10251                    (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10252            if (pkgSetting.getInstantApp(userId)) {
10253                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10254            }
10255        }
10256    }
10257
10258    /**
10259     * Returns the "real" name of the package.
10260     * <p>This may differ from the package's actual name if the application has already
10261     * been installed under one of this package's original names.
10262     */
10263    private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg,
10264            @Nullable String renamedPkgName) {
10265        if (isPackageRenamed(pkg, renamedPkgName)) {
10266            return pkg.mRealPackage;
10267        }
10268        return null;
10269    }
10270
10271    /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */
10272    private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg,
10273            @Nullable String renamedPkgName) {
10274        return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName);
10275    }
10276
10277    /**
10278     * Returns the original package setting.
10279     * <p>A package can migrate its name during an update. In this scenario, a package
10280     * designates a set of names that it considers as one of its original names.
10281     * <p>An original package must be signed identically and it must have the same
10282     * shared user [if any].
10283     */
10284    @GuardedBy("mPackages")
10285    private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg,
10286            @Nullable String renamedPkgName) {
10287        if (!isPackageRenamed(pkg, renamedPkgName)) {
10288            return null;
10289        }
10290        for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) {
10291            final PackageSetting originalPs =
10292                    mSettings.getPackageLPr(pkg.mOriginalPackages.get(i));
10293            if (originalPs != null) {
10294                // the package is already installed under its original name...
10295                // but, should we use it?
10296                if (!verifyPackageUpdateLPr(originalPs, pkg)) {
10297                    // the new package is incompatible with the original
10298                    continue;
10299                } else if (originalPs.sharedUser != null) {
10300                    if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) {
10301                        // the shared user id is incompatible with the original
10302                        Slog.w(TAG, "Unable to migrate data from " + originalPs.name
10303                                + " to " + pkg.packageName + ": old uid "
10304                                + originalPs.sharedUser.name
10305                                + " differs from " + pkg.mSharedUserId);
10306                        continue;
10307                    }
10308                    // TODO: Add case when shared user id is added [b/28144775]
10309                } else {
10310                    if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10311                            + pkg.packageName + " to old name " + originalPs.name);
10312                }
10313                return originalPs;
10314            }
10315        }
10316        return null;
10317    }
10318
10319    /**
10320     * Renames the package if it was installed under a different name.
10321     * <p>When we've already installed the package under an original name, update
10322     * the new package so we can continue to have the old name.
10323     */
10324    private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg,
10325            @NonNull String renamedPackageName) {
10326        if (pkg.mOriginalPackages == null
10327                || !pkg.mOriginalPackages.contains(renamedPackageName)
10328                || pkg.packageName.equals(renamedPackageName)) {
10329            return;
10330        }
10331        pkg.setPackageName(renamedPackageName);
10332    }
10333
10334    /**
10335     * Just scans the package without any side effects.
10336     * <p>Not entirely true at the moment. There is still one side effect -- this
10337     * method potentially modifies a live {@link PackageSetting} object representing
10338     * the package being scanned. This will be resolved in the future.
10339     *
10340     * @param request Information about the package to be scanned
10341     * @param isUnderFactoryTest Whether or not the device is under factory test
10342     * @param currentTime The current time, in millis
10343     * @return The results of the scan
10344     */
10345    @GuardedBy("mInstallLock")
10346    private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request,
10347            boolean isUnderFactoryTest, long currentTime)
10348                    throws PackageManagerException {
10349        final PackageParser.Package pkg = request.pkg;
10350        PackageSetting pkgSetting = request.pkgSetting;
10351        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10352        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10353        final @ParseFlags int parseFlags = request.parseFlags;
10354        final @ScanFlags int scanFlags = request.scanFlags;
10355        final String realPkgName = request.realPkgName;
10356        final SharedUserSetting sharedUserSetting = request.sharedUserSetting;
10357        final UserHandle user = request.user;
10358        final boolean isPlatformPackage = request.isPlatformPackage;
10359
10360        List<String> changedAbiCodePath = null;
10361
10362        if (DEBUG_PACKAGE_SCANNING) {
10363            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10364                Log.d(TAG, "Scanning package " + pkg.packageName);
10365        }
10366
10367        if (Build.IS_DEBUGGABLE &&
10368                pkg.isPrivileged() &&
10369                SystemProperties.getBoolean(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB, false)) {
10370            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10371        }
10372
10373        // Initialize package source and resource directories
10374        final File scanFile = new File(pkg.codePath);
10375        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10376        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10377
10378        // We keep references to the derived CPU Abis from settings in oder to reuse
10379        // them in the case where we're not upgrading or booting for the first time.
10380        String primaryCpuAbiFromSettings = null;
10381        String secondaryCpuAbiFromSettings = null;
10382        boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0;
10383
10384        if (!needToDeriveAbi) {
10385            if (pkgSetting != null) {
10386                primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString;
10387                secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString;
10388            } else {
10389                // Re-scanning a system package after uninstalling updates; need to derive ABI
10390                needToDeriveAbi = true;
10391            }
10392        }
10393
10394        if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) {
10395            PackageManagerService.reportSettingsProblem(Log.WARN,
10396                    "Package " + pkg.packageName + " shared user changed from "
10397                            + (pkgSetting.sharedUser != null
10398                            ? pkgSetting.sharedUser.name : "<nothing>")
10399                            + " to "
10400                            + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>")
10401                            + "; replacing with new");
10402            pkgSetting = null;
10403        }
10404
10405        String[] usesStaticLibraries = null;
10406        if (pkg.usesStaticLibraries != null) {
10407            usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10408            pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10409        }
10410        final boolean createNewPackage = (pkgSetting == null);
10411        if (createNewPackage) {
10412            final String parentPackageName = (pkg.parentPackage != null)
10413                    ? pkg.parentPackage.packageName : null;
10414            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10415            final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10416            // REMOVE SharedUserSetting from method; update in a separate call
10417            pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting,
10418                    disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile,
10419                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
10420                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10421                    pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10422                    user, true /*allowInstall*/, instantApp, virtualPreload,
10423                    parentPackageName, pkg.getChildPackageNames(),
10424                    UserManagerService.getInstance(), usesStaticLibraries,
10425                    pkg.usesStaticLibrariesVersions);
10426        } else {
10427            // REMOVE SharedUserSetting from method; update in a separate call.
10428            //
10429            // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10430            // secondaryCpuAbi are not known at this point so we always update them
10431            // to null here, only to reset them at a later point.
10432            Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting,
10433                    destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir,
10434                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10435                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10436                    pkg.getChildPackageNames(), UserManagerService.getInstance(),
10437                    usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10438        }
10439        if (createNewPackage && originalPkgSetting != null) {
10440            // This is the initial transition from the original package, so,
10441            // fix up the new package's name now. We must do this after looking
10442            // up the package under its new name, so getPackageLP takes care of
10443            // fiddling things correctly.
10444            pkg.setPackageName(originalPkgSetting.name);
10445
10446            // File a report about this.
10447            String msg = "New package " + pkgSetting.realName
10448                    + " renamed to replace old package " + pkgSetting.name;
10449            reportSettingsProblem(Log.WARN, msg);
10450        }
10451
10452        final int userId = (user == null ? UserHandle.USER_SYSTEM : user.getIdentifier());
10453        // for existing packages, change the install state; but, only if it's explicitly specified
10454        if (!createNewPackage) {
10455            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10456            final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
10457            setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
10458        }
10459
10460        if (disabledPkgSetting != null) {
10461            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10462        }
10463
10464        // Apps which share a sharedUserId must be placed in the same selinux domain. If this
10465        // package is the first app installed as this shared user, set seInfoTargetSdkVersion to its
10466        // targetSdkVersion. These are later adjusted in PackageManagerService's constructor to be
10467        // the lowest targetSdkVersion of all apps within the shared user, which corresponds to the
10468        // least restrictive selinux domain.
10469        // NOTE: As new packages are installed / updated, the shared user's seinfoTargetSdkVersion
10470        // will NOT be modified until next boot, even if a lower targetSdkVersion is used. This
10471        // ensures that all packages continue to run in the same selinux domain.
10472        final int targetSdkVersion =
10473            ((sharedUserSetting != null) && (sharedUserSetting.packages.size() != 0)) ?
10474            sharedUserSetting.seInfoTargetSdkVersion : pkg.applicationInfo.targetSdkVersion;
10475        // TODO(b/71593002): isPrivileged for sharedUser and appInfo should never be out of sync.
10476        // They currently can be if the sharedUser apps are signed with the platform key.
10477        final boolean isPrivileged = (sharedUserSetting != null) ?
10478            sharedUserSetting.isPrivileged() | pkg.isPrivileged() : pkg.isPrivileged();
10479
10480        pkg.applicationInfo.seInfo = SELinuxMMAC.getSeInfo(pkg, isPrivileged,
10481                pkg.applicationInfo.targetSandboxVersion, targetSdkVersion);
10482        pkg.applicationInfo.seInfoUser = SELinuxUtil.assignSeinfoUser(pkgSetting.readUserState(
10483                userId == UserHandle.USER_ALL ? UserHandle.USER_SYSTEM : userId));
10484
10485        pkg.mExtras = pkgSetting;
10486        pkg.applicationInfo.processName = fixProcessName(
10487                pkg.applicationInfo.packageName,
10488                pkg.applicationInfo.processName);
10489
10490        if (!isPlatformPackage) {
10491            // Get all of our default paths setup
10492            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10493        }
10494
10495        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10496
10497        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10498            if (needToDeriveAbi) {
10499                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10500                final boolean extractNativeLibs = !pkg.isLibrary();
10501                derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs);
10502                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10503
10504                // Some system apps still use directory structure for native libraries
10505                // in which case we might end up not detecting abi solely based on apk
10506                // structure. Try to detect abi based on directory structure.
10507                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10508                        pkg.applicationInfo.primaryCpuAbi == null) {
10509                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10510                    setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10511                }
10512            } else {
10513                // This is not a first boot or an upgrade, don't bother deriving the
10514                // ABI during the scan. Instead, trust the value that was stored in the
10515                // package setting.
10516                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10517                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10518
10519                setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10520
10521                if (DEBUG_ABI_SELECTION) {
10522                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10523                            pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10524                            pkg.applicationInfo.secondaryCpuAbi);
10525                }
10526            }
10527        } else {
10528            if ((scanFlags & SCAN_MOVE) != 0) {
10529                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10530                // but we already have this packages package info in the PackageSetting. We just
10531                // use that and derive the native library path based on the new codepath.
10532                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10533                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10534            }
10535
10536            // Set native library paths again. For moves, the path will be updated based on the
10537            // ABIs we've determined above. For non-moves, the path will be updated based on the
10538            // ABIs we determined during compilation, but the path will depend on the final
10539            // package path (after the rename away from the stage path).
10540            setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10541        }
10542
10543        // This is a special case for the "system" package, where the ABI is
10544        // dictated by the zygote configuration (and init.rc). We should keep track
10545        // of this ABI so that we can deal with "normal" applications that run under
10546        // the same UID correctly.
10547        if (isPlatformPackage) {
10548            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10549                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10550        }
10551
10552        // If there's a mismatch between the abi-override in the package setting
10553        // and the abiOverride specified for the install. Warn about this because we
10554        // would've already compiled the app without taking the package setting into
10555        // account.
10556        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10557            if (cpuAbiOverride == null && pkg.packageName != null) {
10558                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10559                        " for package " + pkg.packageName);
10560            }
10561        }
10562
10563        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10564        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10565        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10566
10567        // Copy the derived override back to the parsed package, so that we can
10568        // update the package settings accordingly.
10569        pkg.cpuAbiOverride = cpuAbiOverride;
10570
10571        if (DEBUG_ABI_SELECTION) {
10572            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName
10573                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10574                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10575        }
10576
10577        // Push the derived path down into PackageSettings so we know what to
10578        // clean up at uninstall time.
10579        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10580
10581        if (DEBUG_ABI_SELECTION) {
10582            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10583                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10584                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10585        }
10586
10587        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10588            // We don't do this here during boot because we can do it all
10589            // at once after scanning all existing packages.
10590            //
10591            // We also do this *before* we perform dexopt on this package, so that
10592            // we can avoid redundant dexopts, and also to make sure we've got the
10593            // code and package path correct.
10594            changedAbiCodePath =
10595                    adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10596        }
10597
10598        if (isUnderFactoryTest && pkg.requestedPermissions.contains(
10599                android.Manifest.permission.FACTORY_TEST)) {
10600            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10601        }
10602
10603        if (isSystemApp(pkg)) {
10604            pkgSetting.isOrphaned = true;
10605        }
10606
10607        // Take care of first install / last update times.
10608        final long scanFileTime = getLastModifiedTime(pkg);
10609        if (currentTime != 0) {
10610            if (pkgSetting.firstInstallTime == 0) {
10611                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10612            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10613                pkgSetting.lastUpdateTime = currentTime;
10614            }
10615        } else if (pkgSetting.firstInstallTime == 0) {
10616            // We need *something*.  Take time time stamp of the file.
10617            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10618        } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10619            if (scanFileTime != pkgSetting.timeStamp) {
10620                // A package on the system image has changed; consider this
10621                // to be an update.
10622                pkgSetting.lastUpdateTime = scanFileTime;
10623            }
10624        }
10625        pkgSetting.setTimeStamp(scanFileTime);
10626
10627        pkgSetting.pkg = pkg;
10628        pkgSetting.pkgFlags = pkg.applicationInfo.flags;
10629        if (pkg.getLongVersionCode() != pkgSetting.versionCode) {
10630            pkgSetting.versionCode = pkg.getLongVersionCode();
10631        }
10632        // Update volume if needed
10633        final String volumeUuid = pkg.applicationInfo.volumeUuid;
10634        if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) {
10635            Slog.i(PackageManagerService.TAG,
10636                    "Update" + (pkgSetting.isSystem() ? " system" : "")
10637                    + " package " + pkg.packageName
10638                    + " volume from " + pkgSetting.volumeUuid
10639                    + " to " + volumeUuid);
10640            pkgSetting.volumeUuid = volumeUuid;
10641        }
10642
10643        return new ScanResult(true, pkgSetting, changedAbiCodePath);
10644    }
10645
10646    /**
10647     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10648     */
10649    private static boolean apkHasCode(String fileName) {
10650        StrictJarFile jarFile = null;
10651        try {
10652            jarFile = new StrictJarFile(fileName,
10653                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10654            return jarFile.findEntry("classes.dex") != null;
10655        } catch (IOException ignore) {
10656        } finally {
10657            try {
10658                if (jarFile != null) {
10659                    jarFile.close();
10660                }
10661            } catch (IOException ignore) {}
10662        }
10663        return false;
10664    }
10665
10666    /**
10667     * Enforces code policy for the package. This ensures that if an APK has
10668     * declared hasCode="true" in its manifest that the APK actually contains
10669     * code.
10670     *
10671     * @throws PackageManagerException If bytecode could not be found when it should exist
10672     */
10673    private static void assertCodePolicy(PackageParser.Package pkg)
10674            throws PackageManagerException {
10675        final boolean shouldHaveCode =
10676                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10677        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10678            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10679                    "Package " + pkg.baseCodePath + " code is missing");
10680        }
10681
10682        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10683            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10684                final boolean splitShouldHaveCode =
10685                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10686                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10687                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10688                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10689                }
10690            }
10691        }
10692    }
10693
10694    /**
10695     * Applies policy to the parsed package based upon the given policy flags.
10696     * Ensures the package is in a good state.
10697     * <p>
10698     * Implementation detail: This method must NOT have any side effect. It would
10699     * ideally be static, but, it requires locks to read system state.
10700     */
10701    private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10702            final @ScanFlags int scanFlags, PackageParser.Package platformPkg) {
10703        if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10704            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10705            if (pkg.applicationInfo.isDirectBootAware()) {
10706                // we're direct boot aware; set for all components
10707                for (PackageParser.Service s : pkg.services) {
10708                    s.info.encryptionAware = s.info.directBootAware = true;
10709                }
10710                for (PackageParser.Provider p : pkg.providers) {
10711                    p.info.encryptionAware = p.info.directBootAware = true;
10712                }
10713                for (PackageParser.Activity a : pkg.activities) {
10714                    a.info.encryptionAware = a.info.directBootAware = true;
10715                }
10716                for (PackageParser.Activity r : pkg.receivers) {
10717                    r.info.encryptionAware = r.info.directBootAware = true;
10718                }
10719            }
10720            if (compressedFileExists(pkg.codePath)) {
10721                pkg.isStub = true;
10722            }
10723        } else {
10724            // non system apps can't be flagged as core
10725            pkg.coreApp = false;
10726            // clear flags not applicable to regular apps
10727            pkg.applicationInfo.flags &=
10728                    ~ApplicationInfo.FLAG_PERSISTENT;
10729            pkg.applicationInfo.privateFlags &=
10730                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10731            pkg.applicationInfo.privateFlags &=
10732                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10733            // cap permission priorities
10734            if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) {
10735                for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) {
10736                    pkg.permissionGroups.get(i).info.priority = 0;
10737                }
10738            }
10739        }
10740        if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10741            // clear protected broadcasts
10742            pkg.protectedBroadcasts = null;
10743            // ignore export request for single user receivers
10744            if (pkg.receivers != null) {
10745                for (int i = pkg.receivers.size() - 1; i >= 0; --i) {
10746                    final PackageParser.Activity receiver = pkg.receivers.get(i);
10747                    if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) {
10748                        receiver.info.exported = false;
10749                    }
10750                }
10751            }
10752            // ignore export request for single user services
10753            if (pkg.services != null) {
10754                for (int i = pkg.services.size() - 1; i >= 0; --i) {
10755                    final PackageParser.Service service = pkg.services.get(i);
10756                    if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
10757                        service.info.exported = false;
10758                    }
10759                }
10760            }
10761            // ignore export request for single user providers
10762            if (pkg.providers != null) {
10763                for (int i = pkg.providers.size() - 1; i >= 0; --i) {
10764                    final PackageParser.Provider provider = pkg.providers.get(i);
10765                    if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) {
10766                        provider.info.exported = false;
10767                    }
10768                }
10769            }
10770        }
10771
10772        if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) {
10773            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10774        }
10775
10776        if ((scanFlags & SCAN_AS_OEM) != 0) {
10777            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10778        }
10779
10780        if ((scanFlags & SCAN_AS_VENDOR) != 0) {
10781            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR;
10782        }
10783
10784        if ((scanFlags & SCAN_AS_PRODUCT) != 0) {
10785            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRODUCT;
10786        }
10787
10788        // Check if the package is signed with the same key as the platform package.
10789        if (PLATFORM_PACKAGE_NAME.equals(pkg.packageName) ||
10790                (platformPkg != null && compareSignatures(
10791                        platformPkg.mSigningDetails.signatures,
10792                        pkg.mSigningDetails.signatures) == PackageManager.SIGNATURE_MATCH)) {
10793            pkg.applicationInfo.privateFlags |=
10794                ApplicationInfo.PRIVATE_FLAG_SIGNED_WITH_PLATFORM_KEY;
10795        }
10796
10797        if (!isSystemApp(pkg)) {
10798            // Only system apps can use these features.
10799            pkg.mOriginalPackages = null;
10800            pkg.mRealPackage = null;
10801            pkg.mAdoptPermissions = null;
10802        }
10803    }
10804
10805    private static @NonNull <T> T assertNotNull(@Nullable T object, String message)
10806            throws PackageManagerException {
10807        if (object == null) {
10808            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, message);
10809        }
10810        return object;
10811    }
10812
10813    /**
10814     * Asserts the parsed package is valid according to the given policy. If the
10815     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10816     * <p>
10817     * Implementation detail: This method must NOT have any side effects. It would
10818     * ideally be static, but, it requires locks to read system state.
10819     *
10820     * @throws PackageManagerException If the package fails any of the validation checks
10821     */
10822    private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10823            final @ScanFlags int scanFlags)
10824                    throws PackageManagerException {
10825        if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10826            assertCodePolicy(pkg);
10827        }
10828
10829        if (pkg.applicationInfo.getCodePath() == null ||
10830                pkg.applicationInfo.getResourcePath() == null) {
10831            // Bail out. The resource and code paths haven't been set.
10832            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10833                    "Code and resource paths haven't been set correctly");
10834        }
10835
10836        // Make sure we're not adding any bogus keyset info
10837        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10838        ksms.assertScannedPackageValid(pkg);
10839
10840        synchronized (mPackages) {
10841            // The special "android" package can only be defined once
10842            if (pkg.packageName.equals("android")) {
10843                if (mAndroidApplication != null) {
10844                    Slog.w(TAG, "*************************************************");
10845                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10846                    Slog.w(TAG, " codePath=" + pkg.codePath);
10847                    Slog.w(TAG, "*************************************************");
10848                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10849                            "Core android package being redefined.  Skipping.");
10850                }
10851            }
10852
10853            // A package name must be unique; don't allow duplicates
10854            if (mPackages.containsKey(pkg.packageName)) {
10855                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10856                        "Application package " + pkg.packageName
10857                        + " already installed.  Skipping duplicate.");
10858            }
10859
10860            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10861                // Static libs have a synthetic package name containing the version
10862                // but we still want the base name to be unique.
10863                if (mPackages.containsKey(pkg.manifestPackageName)) {
10864                    throw new PackageManagerException(
10865                            "Duplicate static shared lib provider package");
10866                }
10867
10868                // Static shared libraries should have at least O target SDK
10869                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10870                    throw new PackageManagerException(
10871                            "Packages declaring static-shared libs must target O SDK or higher");
10872                }
10873
10874                // Package declaring static a shared lib cannot be instant apps
10875                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10876                    throw new PackageManagerException(
10877                            "Packages declaring static-shared libs cannot be instant apps");
10878                }
10879
10880                // Package declaring static a shared lib cannot be renamed since the package
10881                // name is synthetic and apps can't code around package manager internals.
10882                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10883                    throw new PackageManagerException(
10884                            "Packages declaring static-shared libs cannot be renamed");
10885                }
10886
10887                // Package declaring static a shared lib cannot declare child packages
10888                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10889                    throw new PackageManagerException(
10890                            "Packages declaring static-shared libs cannot have child packages");
10891                }
10892
10893                // Package declaring static a shared lib cannot declare dynamic libs
10894                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10895                    throw new PackageManagerException(
10896                            "Packages declaring static-shared libs cannot declare dynamic libs");
10897                }
10898
10899                // Package declaring static a shared lib cannot declare shared users
10900                if (pkg.mSharedUserId != null) {
10901                    throw new PackageManagerException(
10902                            "Packages declaring static-shared libs cannot declare shared users");
10903                }
10904
10905                // Static shared libs cannot declare activities
10906                if (!pkg.activities.isEmpty()) {
10907                    throw new PackageManagerException(
10908                            "Static shared libs cannot declare activities");
10909                }
10910
10911                // Static shared libs cannot declare services
10912                if (!pkg.services.isEmpty()) {
10913                    throw new PackageManagerException(
10914                            "Static shared libs cannot declare services");
10915                }
10916
10917                // Static shared libs cannot declare providers
10918                if (!pkg.providers.isEmpty()) {
10919                    throw new PackageManagerException(
10920                            "Static shared libs cannot declare content providers");
10921                }
10922
10923                // Static shared libs cannot declare receivers
10924                if (!pkg.receivers.isEmpty()) {
10925                    throw new PackageManagerException(
10926                            "Static shared libs cannot declare broadcast receivers");
10927                }
10928
10929                // Static shared libs cannot declare permission groups
10930                if (!pkg.permissionGroups.isEmpty()) {
10931                    throw new PackageManagerException(
10932                            "Static shared libs cannot declare permission groups");
10933                }
10934
10935                // Static shared libs cannot declare permissions
10936                if (!pkg.permissions.isEmpty()) {
10937                    throw new PackageManagerException(
10938                            "Static shared libs cannot declare permissions");
10939                }
10940
10941                // Static shared libs cannot declare protected broadcasts
10942                if (pkg.protectedBroadcasts != null) {
10943                    throw new PackageManagerException(
10944                            "Static shared libs cannot declare protected broadcasts");
10945                }
10946
10947                // Static shared libs cannot be overlay targets
10948                if (pkg.mOverlayTarget != null) {
10949                    throw new PackageManagerException(
10950                            "Static shared libs cannot be overlay targets");
10951                }
10952
10953                // The version codes must be ordered as lib versions
10954                long minVersionCode = Long.MIN_VALUE;
10955                long maxVersionCode = Long.MAX_VALUE;
10956
10957                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10958                        pkg.staticSharedLibName);
10959                if (versionedLib != null) {
10960                    final int versionCount = versionedLib.size();
10961                    for (int i = 0; i < versionCount; i++) {
10962                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10963                        final long libVersionCode = libInfo.getDeclaringPackage()
10964                                .getLongVersionCode();
10965                        if (libInfo.getLongVersion() <  pkg.staticSharedLibVersion) {
10966                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10967                        } else if (libInfo.getLongVersion() >  pkg.staticSharedLibVersion) {
10968                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10969                        } else {
10970                            minVersionCode = maxVersionCode = libVersionCode;
10971                            break;
10972                        }
10973                    }
10974                }
10975                if (pkg.getLongVersionCode() < minVersionCode
10976                        || pkg.getLongVersionCode() > maxVersionCode) {
10977                    throw new PackageManagerException("Static shared"
10978                            + " lib version codes must be ordered as lib versions");
10979                }
10980            }
10981
10982            // Only privileged apps and updated privileged apps can add child packages.
10983            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10984                if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10985                    throw new PackageManagerException("Only privileged apps can add child "
10986                            + "packages. Ignoring package " + pkg.packageName);
10987                }
10988                final int childCount = pkg.childPackages.size();
10989                for (int i = 0; i < childCount; i++) {
10990                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10991                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10992                            childPkg.packageName)) {
10993                        throw new PackageManagerException("Can't override child of "
10994                                + "another disabled app. Ignoring package " + pkg.packageName);
10995                    }
10996                }
10997            }
10998
10999            // If we're only installing presumed-existing packages, require that the
11000            // scanned APK is both already known and at the path previously established
11001            // for it.  Previously unknown packages we pick up normally, but if we have an
11002            // a priori expectation about this package's install presence, enforce it.
11003            // With a singular exception for new system packages. When an OTA contains
11004            // a new system package, we allow the codepath to change from a system location
11005            // to the user-installed location. If we don't allow this change, any newer,
11006            // user-installed version of the application will be ignored.
11007            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
11008                if (mExpectingBetter.containsKey(pkg.packageName)) {
11009                    logCriticalInfo(Log.WARN,
11010                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
11011                } else {
11012                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
11013                    if (known != null) {
11014                        if (DEBUG_PACKAGE_SCANNING) {
11015                            Log.d(TAG, "Examining " + pkg.codePath
11016                                    + " and requiring known paths " + known.codePathString
11017                                    + " & " + known.resourcePathString);
11018                        }
11019                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
11020                                || !pkg.applicationInfo.getResourcePath().equals(
11021                                        known.resourcePathString)) {
11022                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
11023                                    "Application package " + pkg.packageName
11024                                    + " found at " + pkg.applicationInfo.getCodePath()
11025                                    + " but expected at " + known.codePathString
11026                                    + "; ignoring.");
11027                        }
11028                    } else {
11029                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11030                                "Application package " + pkg.packageName
11031                                + " not found; ignoring.");
11032                    }
11033                }
11034            }
11035
11036            // Verify that this new package doesn't have any content providers
11037            // that conflict with existing packages.  Only do this if the
11038            // package isn't already installed, since we don't want to break
11039            // things that are installed.
11040            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11041                final int N = pkg.providers.size();
11042                int i;
11043                for (i=0; i<N; i++) {
11044                    PackageParser.Provider p = pkg.providers.get(i);
11045                    if (p.info.authority != null) {
11046                        String names[] = p.info.authority.split(";");
11047                        for (int j = 0; j < names.length; j++) {
11048                            if (mProvidersByAuthority.containsKey(names[j])) {
11049                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11050                                final String otherPackageName =
11051                                        ((other != null && other.getComponentName() != null) ?
11052                                                other.getComponentName().getPackageName() : "?");
11053                                throw new PackageManagerException(
11054                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11055                                        "Can't install because provider name " + names[j]
11056                                                + " (in package " + pkg.applicationInfo.packageName
11057                                                + ") is already used by " + otherPackageName);
11058                            }
11059                        }
11060                    }
11061                }
11062            }
11063
11064            // Verify that packages sharing a user with a privileged app are marked as privileged.
11065            if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) {
11066                SharedUserSetting sharedUserSetting = null;
11067                try {
11068                    sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
11069                } catch (PackageManagerException ignore) {}
11070                if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
11071                    // Exempt SharedUsers signed with the platform key.
11072                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
11073                    if ((platformPkgSetting.signatures.mSigningDetails
11074                            != PackageParser.SigningDetails.UNKNOWN)
11075                            && (compareSignatures(
11076                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11077                                    pkg.mSigningDetails.signatures)
11078                                            != PackageManager.SIGNATURE_MATCH)) {
11079                        throw new PackageManagerException("Apps that share a user with a " +
11080                                "privileged app must themselves be marked as privileged. " +
11081                                pkg.packageName + " shares privileged user " +
11082                                pkg.mSharedUserId + ".");
11083                    }
11084                }
11085            }
11086
11087            // Apply policies specific for runtime resource overlays (RROs).
11088            if (pkg.mOverlayTarget != null) {
11089                // System overlays have some restrictions on their use of the 'static' state.
11090                if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
11091                    // We are scanning a system overlay. This can be the first scan of the
11092                    // system/vendor/oem partition, or an update to the system overlay.
11093                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
11094                        // This must be an update to a system overlay.
11095                        final PackageSetting previousPkg = assertNotNull(
11096                                mSettings.getPackageLPr(pkg.packageName),
11097                                "previous package state not present");
11098
11099                        // Static overlays cannot be updated.
11100                        if (previousPkg.pkg.mOverlayIsStatic) {
11101                            throw new PackageManagerException("Overlay " + pkg.packageName +
11102                                    " is static and cannot be upgraded.");
11103                        // Non-static overlays cannot be converted to static overlays.
11104                        } else if (pkg.mOverlayIsStatic) {
11105                            throw new PackageManagerException("Overlay " + pkg.packageName +
11106                                    " cannot be upgraded into a static overlay.");
11107                        }
11108                    }
11109                } else {
11110                    // The overlay is a non-system overlay. Non-system overlays cannot be static.
11111                    if (pkg.mOverlayIsStatic) {
11112                        throw new PackageManagerException("Overlay " + pkg.packageName +
11113                                " is static but not pre-installed.");
11114                    }
11115
11116                    // The only case where we allow installation of a non-system overlay is when
11117                    // its signature is signed with the platform certificate.
11118                    PackageSetting platformPkgSetting = mSettings.getPackageLPr("android");
11119                    if ((platformPkgSetting.signatures.mSigningDetails
11120                            != PackageParser.SigningDetails.UNKNOWN)
11121                            && (compareSignatures(
11122                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11123                                    pkg.mSigningDetails.signatures)
11124                                            != PackageManager.SIGNATURE_MATCH)) {
11125                        throw new PackageManagerException("Overlay " + pkg.packageName +
11126                                " must be signed with the platform certificate.");
11127                    }
11128                }
11129            }
11130        }
11131    }
11132
11133    private boolean addSharedLibraryLPw(String path, String apk, String name, long version,
11134            int type, String declaringPackageName, long declaringVersionCode) {
11135        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11136        if (versionedLib == null) {
11137            versionedLib = new LongSparseArray<>();
11138            mSharedLibraries.put(name, versionedLib);
11139            if (type == SharedLibraryInfo.TYPE_STATIC) {
11140                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11141            }
11142        } else if (versionedLib.indexOfKey(version) >= 0) {
11143            return false;
11144        }
11145        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11146                version, type, declaringPackageName, declaringVersionCode);
11147        versionedLib.put(version, libEntry);
11148        return true;
11149    }
11150
11151    private boolean removeSharedLibraryLPw(String name, long version) {
11152        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11153        if (versionedLib == null) {
11154            return false;
11155        }
11156        final int libIdx = versionedLib.indexOfKey(version);
11157        if (libIdx < 0) {
11158            return false;
11159        }
11160        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11161        versionedLib.remove(version);
11162        if (versionedLib.size() <= 0) {
11163            mSharedLibraries.remove(name);
11164            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11165                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11166                        .getPackageName());
11167            }
11168        }
11169        return true;
11170    }
11171
11172    /**
11173     * Adds a scanned package to the system. When this method is finished, the package will
11174     * be available for query, resolution, etc...
11175     */
11176    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11177            UserHandle user, final @ScanFlags int scanFlags, boolean chatty) {
11178        final String pkgName = pkg.packageName;
11179        if (mCustomResolverComponentName != null &&
11180                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11181            setUpCustomResolverActivity(pkg);
11182        }
11183
11184        if (pkg.packageName.equals("android")) {
11185            synchronized (mPackages) {
11186                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11187                    // Set up information for our fall-back user intent resolution activity.
11188                    mPlatformPackage = pkg;
11189                    pkg.mVersionCode = mSdkVersion;
11190                    pkg.mVersionCodeMajor = 0;
11191                    mAndroidApplication = pkg.applicationInfo;
11192                    if (!mResolverReplaced) {
11193                        mResolveActivity.applicationInfo = mAndroidApplication;
11194                        mResolveActivity.name = ResolverActivity.class.getName();
11195                        mResolveActivity.packageName = mAndroidApplication.packageName;
11196                        mResolveActivity.processName = "system:ui";
11197                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11198                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11199                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11200                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11201                        mResolveActivity.exported = true;
11202                        mResolveActivity.enabled = true;
11203                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11204                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11205                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11206                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11207                                | ActivityInfo.CONFIG_ORIENTATION
11208                                | ActivityInfo.CONFIG_KEYBOARD
11209                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11210                        mResolveInfo.activityInfo = mResolveActivity;
11211                        mResolveInfo.priority = 0;
11212                        mResolveInfo.preferredOrder = 0;
11213                        mResolveInfo.match = 0;
11214                        mResolveComponentName = new ComponentName(
11215                                mAndroidApplication.packageName, mResolveActivity.name);
11216                    }
11217                }
11218            }
11219        }
11220
11221        ArrayList<PackageParser.Package> clientLibPkgs = null;
11222        // writer
11223        synchronized (mPackages) {
11224            boolean hasStaticSharedLibs = false;
11225
11226            // Any app can add new static shared libraries
11227            if (pkg.staticSharedLibName != null) {
11228                // Static shared libs don't allow renaming as they have synthetic package
11229                // names to allow install of multiple versions, so use name from manifest.
11230                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11231                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11232                        pkg.manifestPackageName, pkg.getLongVersionCode())) {
11233                    hasStaticSharedLibs = true;
11234                } else {
11235                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11236                                + pkg.staticSharedLibName + " already exists; skipping");
11237                }
11238                // Static shared libs cannot be updated once installed since they
11239                // use synthetic package name which includes the version code, so
11240                // not need to update other packages's shared lib dependencies.
11241            }
11242
11243            if (!hasStaticSharedLibs
11244                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11245                // Only system apps can add new dynamic shared libraries.
11246                if (pkg.libraryNames != null) {
11247                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11248                        String name = pkg.libraryNames.get(i);
11249                        boolean allowed = false;
11250                        if (pkg.isUpdatedSystemApp()) {
11251                            // New library entries can only be added through the
11252                            // system image.  This is important to get rid of a lot
11253                            // of nasty edge cases: for example if we allowed a non-
11254                            // system update of the app to add a library, then uninstalling
11255                            // the update would make the library go away, and assumptions
11256                            // we made such as through app install filtering would now
11257                            // have allowed apps on the device which aren't compatible
11258                            // with it.  Better to just have the restriction here, be
11259                            // conservative, and create many fewer cases that can negatively
11260                            // impact the user experience.
11261                            final PackageSetting sysPs = mSettings
11262                                    .getDisabledSystemPkgLPr(pkg.packageName);
11263                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11264                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11265                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11266                                        allowed = true;
11267                                        break;
11268                                    }
11269                                }
11270                            }
11271                        } else {
11272                            allowed = true;
11273                        }
11274                        if (allowed) {
11275                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11276                                    SharedLibraryInfo.VERSION_UNDEFINED,
11277                                    SharedLibraryInfo.TYPE_DYNAMIC,
11278                                    pkg.packageName, pkg.getLongVersionCode())) {
11279                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11280                                        + name + " already exists; skipping");
11281                            }
11282                        } else {
11283                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11284                                    + name + " that is not declared on system image; skipping");
11285                        }
11286                    }
11287
11288                    if ((scanFlags & SCAN_BOOTING) == 0) {
11289                        // If we are not booting, we need to update any applications
11290                        // that are clients of our shared library.  If we are booting,
11291                        // this will all be done once the scan is complete.
11292                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11293                    }
11294                }
11295            }
11296        }
11297
11298        if ((scanFlags & SCAN_BOOTING) != 0) {
11299            // No apps can run during boot scan, so they don't need to be frozen
11300        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11301            // Caller asked to not kill app, so it's probably not frozen
11302        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11303            // Caller asked us to ignore frozen check for some reason; they
11304            // probably didn't know the package name
11305        } else {
11306            // We're doing major surgery on this package, so it better be frozen
11307            // right now to keep it from launching
11308            checkPackageFrozen(pkgName);
11309        }
11310
11311        // Also need to kill any apps that are dependent on the library.
11312        if (clientLibPkgs != null) {
11313            for (int i=0; i<clientLibPkgs.size(); i++) {
11314                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11315                killApplication(clientPkg.applicationInfo.packageName,
11316                        clientPkg.applicationInfo.uid, "update lib");
11317            }
11318        }
11319
11320        // writer
11321        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11322
11323        synchronized (mPackages) {
11324            // We don't expect installation to fail beyond this point
11325
11326            // Add the new setting to mSettings
11327            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11328            // Add the new setting to mPackages
11329            mPackages.put(pkg.applicationInfo.packageName, pkg);
11330            // Make sure we don't accidentally delete its data.
11331            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11332            while (iter.hasNext()) {
11333                PackageCleanItem item = iter.next();
11334                if (pkgName.equals(item.packageName)) {
11335                    iter.remove();
11336                }
11337            }
11338
11339            // Add the package's KeySets to the global KeySetManagerService
11340            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11341            ksms.addScannedPackageLPw(pkg);
11342
11343            int N = pkg.providers.size();
11344            StringBuilder r = null;
11345            int i;
11346            for (i=0; i<N; i++) {
11347                PackageParser.Provider p = pkg.providers.get(i);
11348                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11349                        p.info.processName);
11350                mProviders.addProvider(p);
11351                p.syncable = p.info.isSyncable;
11352                if (p.info.authority != null) {
11353                    String names[] = p.info.authority.split(";");
11354                    p.info.authority = null;
11355                    for (int j = 0; j < names.length; j++) {
11356                        if (j == 1 && p.syncable) {
11357                            // We only want the first authority for a provider to possibly be
11358                            // syncable, so if we already added this provider using a different
11359                            // authority clear the syncable flag. We copy the provider before
11360                            // changing it because the mProviders object contains a reference
11361                            // to a provider that we don't want to change.
11362                            // Only do this for the second authority since the resulting provider
11363                            // object can be the same for all future authorities for this provider.
11364                            p = new PackageParser.Provider(p);
11365                            p.syncable = false;
11366                        }
11367                        if (!mProvidersByAuthority.containsKey(names[j])) {
11368                            mProvidersByAuthority.put(names[j], p);
11369                            if (p.info.authority == null) {
11370                                p.info.authority = names[j];
11371                            } else {
11372                                p.info.authority = p.info.authority + ";" + names[j];
11373                            }
11374                            if (DEBUG_PACKAGE_SCANNING) {
11375                                if (chatty)
11376                                    Log.d(TAG, "Registered content provider: " + names[j]
11377                                            + ", className = " + p.info.name + ", isSyncable = "
11378                                            + p.info.isSyncable);
11379                            }
11380                        } else {
11381                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11382                            Slog.w(TAG, "Skipping provider name " + names[j] +
11383                                    " (in package " + pkg.applicationInfo.packageName +
11384                                    "): name already used by "
11385                                    + ((other != null && other.getComponentName() != null)
11386                                            ? other.getComponentName().getPackageName() : "?"));
11387                        }
11388                    }
11389                }
11390                if (chatty) {
11391                    if (r == null) {
11392                        r = new StringBuilder(256);
11393                    } else {
11394                        r.append(' ');
11395                    }
11396                    r.append(p.info.name);
11397                }
11398            }
11399            if (r != null) {
11400                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11401            }
11402
11403            N = pkg.services.size();
11404            r = null;
11405            for (i=0; i<N; i++) {
11406                PackageParser.Service s = pkg.services.get(i);
11407                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11408                        s.info.processName);
11409                mServices.addService(s);
11410                if (chatty) {
11411                    if (r == null) {
11412                        r = new StringBuilder(256);
11413                    } else {
11414                        r.append(' ');
11415                    }
11416                    r.append(s.info.name);
11417                }
11418            }
11419            if (r != null) {
11420                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11421            }
11422
11423            N = pkg.receivers.size();
11424            r = null;
11425            for (i=0; i<N; i++) {
11426                PackageParser.Activity a = pkg.receivers.get(i);
11427                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11428                        a.info.processName);
11429                mReceivers.addActivity(a, "receiver");
11430                if (chatty) {
11431                    if (r == null) {
11432                        r = new StringBuilder(256);
11433                    } else {
11434                        r.append(' ');
11435                    }
11436                    r.append(a.info.name);
11437                }
11438            }
11439            if (r != null) {
11440                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11441            }
11442
11443            N = pkg.activities.size();
11444            r = null;
11445            for (i=0; i<N; i++) {
11446                PackageParser.Activity a = pkg.activities.get(i);
11447                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11448                        a.info.processName);
11449                mActivities.addActivity(a, "activity");
11450                if (chatty) {
11451                    if (r == null) {
11452                        r = new StringBuilder(256);
11453                    } else {
11454                        r.append(' ');
11455                    }
11456                    r.append(a.info.name);
11457                }
11458            }
11459            if (r != null) {
11460                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11461            }
11462
11463            // Don't allow ephemeral applications to define new permissions groups.
11464            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11465                Slog.w(TAG, "Permission groups from package " + pkg.packageName
11466                        + " ignored: instant apps cannot define new permission groups.");
11467            } else {
11468                mPermissionManager.addAllPermissionGroups(pkg, chatty);
11469            }
11470
11471            // Don't allow ephemeral applications to define new permissions.
11472            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11473                Slog.w(TAG, "Permissions from package " + pkg.packageName
11474                        + " ignored: instant apps cannot define new permissions.");
11475            } else {
11476                mPermissionManager.addAllPermissions(pkg, chatty);
11477            }
11478
11479            N = pkg.instrumentation.size();
11480            r = null;
11481            for (i=0; i<N; i++) {
11482                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11483                a.info.packageName = pkg.applicationInfo.packageName;
11484                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11485                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11486                a.info.splitNames = pkg.splitNames;
11487                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11488                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11489                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11490                a.info.dataDir = pkg.applicationInfo.dataDir;
11491                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11492                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11493                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11494                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11495                mInstrumentation.put(a.getComponentName(), a);
11496                if (chatty) {
11497                    if (r == null) {
11498                        r = new StringBuilder(256);
11499                    } else {
11500                        r.append(' ');
11501                    }
11502                    r.append(a.info.name);
11503                }
11504            }
11505            if (r != null) {
11506                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11507            }
11508
11509            if (pkg.protectedBroadcasts != null) {
11510                N = pkg.protectedBroadcasts.size();
11511                synchronized (mProtectedBroadcasts) {
11512                    for (i = 0; i < N; i++) {
11513                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11514                    }
11515                }
11516            }
11517        }
11518
11519        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11520    }
11521
11522    /**
11523     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11524     * is derived purely on the basis of the contents of {@code scanFile} and
11525     * {@code cpuAbiOverride}.
11526     *
11527     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11528     */
11529    private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride,
11530            boolean extractLibs)
11531                    throws PackageManagerException {
11532        // Give ourselves some initial paths; we'll come back for another
11533        // pass once we've determined ABI below.
11534        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11535
11536        // We would never need to extract libs for forward-locked and external packages,
11537        // since the container service will do it for us. We shouldn't attempt to
11538        // extract libs from system app when it was not updated.
11539        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11540                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11541            extractLibs = false;
11542        }
11543
11544        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11545        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11546
11547        NativeLibraryHelper.Handle handle = null;
11548        try {
11549            handle = NativeLibraryHelper.Handle.create(pkg);
11550            // TODO(multiArch): This can be null for apps that didn't go through the
11551            // usual installation process. We can calculate it again, like we
11552            // do during install time.
11553            //
11554            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11555            // unnecessary.
11556            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11557
11558            // Null out the abis so that they can be recalculated.
11559            pkg.applicationInfo.primaryCpuAbi = null;
11560            pkg.applicationInfo.secondaryCpuAbi = null;
11561            if (isMultiArch(pkg.applicationInfo)) {
11562                // Warn if we've set an abiOverride for multi-lib packages..
11563                // By definition, we need to copy both 32 and 64 bit libraries for
11564                // such packages.
11565                if (pkg.cpuAbiOverride != null
11566                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11567                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11568                }
11569
11570                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11571                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11572                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11573                    if (extractLibs) {
11574                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11575                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11576                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11577                                useIsaSpecificSubdirs);
11578                    } else {
11579                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11580                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11581                    }
11582                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11583                }
11584
11585                // Shared library native code should be in the APK zip aligned
11586                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11587                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11588                            "Shared library native lib extraction not supported");
11589                }
11590
11591                maybeThrowExceptionForMultiArchCopy(
11592                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11593
11594                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11595                    if (extractLibs) {
11596                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11597                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11598                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11599                                useIsaSpecificSubdirs);
11600                    } else {
11601                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11602                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11603                    }
11604                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11605                }
11606
11607                maybeThrowExceptionForMultiArchCopy(
11608                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11609
11610                if (abi64 >= 0) {
11611                    // Shared library native libs should be in the APK zip aligned
11612                    if (extractLibs && pkg.isLibrary()) {
11613                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11614                                "Shared library native lib extraction not supported");
11615                    }
11616                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11617                }
11618
11619                if (abi32 >= 0) {
11620                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11621                    if (abi64 >= 0) {
11622                        if (pkg.use32bitAbi) {
11623                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11624                            pkg.applicationInfo.primaryCpuAbi = abi;
11625                        } else {
11626                            pkg.applicationInfo.secondaryCpuAbi = abi;
11627                        }
11628                    } else {
11629                        pkg.applicationInfo.primaryCpuAbi = abi;
11630                    }
11631                }
11632            } else {
11633                String[] abiList = (cpuAbiOverride != null) ?
11634                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11635
11636                // Enable gross and lame hacks for apps that are built with old
11637                // SDK tools. We must scan their APKs for renderscript bitcode and
11638                // not launch them if it's present. Don't bother checking on devices
11639                // that don't have 64 bit support.
11640                boolean needsRenderScriptOverride = false;
11641                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11642                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11643                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11644                    needsRenderScriptOverride = true;
11645                }
11646
11647                final int copyRet;
11648                if (extractLibs) {
11649                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11650                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11651                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11652                } else {
11653                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11654                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11655                }
11656                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11657
11658                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11659                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11660                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11661                }
11662
11663                if (copyRet >= 0) {
11664                    // Shared libraries that have native libs must be multi-architecture
11665                    if (pkg.isLibrary()) {
11666                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11667                                "Shared library with native libs must be multiarch");
11668                    }
11669                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11670                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11671                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11672                } else if (needsRenderScriptOverride) {
11673                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11674                }
11675            }
11676        } catch (IOException ioe) {
11677            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11678        } finally {
11679            IoUtils.closeQuietly(handle);
11680        }
11681
11682        // Now that we've calculated the ABIs and determined if it's an internal app,
11683        // we will go ahead and populate the nativeLibraryPath.
11684        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11685    }
11686
11687    /**
11688     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11689     * i.e, so that all packages can be run inside a single process if required.
11690     *
11691     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11692     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11693     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11694     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11695     * updating a package that belongs to a shared user.
11696     *
11697     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11698     * adds unnecessary complexity.
11699     */
11700    private static @Nullable List<String> adjustCpuAbisForSharedUserLPw(
11701            Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) {
11702        List<String> changedAbiCodePath = null;
11703        String requiredInstructionSet = null;
11704        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11705            requiredInstructionSet = VMRuntime.getInstructionSet(
11706                     scannedPackage.applicationInfo.primaryCpuAbi);
11707        }
11708
11709        PackageSetting requirer = null;
11710        for (PackageSetting ps : packagesForUser) {
11711            // If packagesForUser contains scannedPackage, we skip it. This will happen
11712            // when scannedPackage is an update of an existing package. Without this check,
11713            // we will never be able to change the ABI of any package belonging to a shared
11714            // user, even if it's compatible with other packages.
11715            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11716                if (ps.primaryCpuAbiString == null) {
11717                    continue;
11718                }
11719
11720                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11721                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11722                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11723                    // this but there's not much we can do.
11724                    String errorMessage = "Instruction set mismatch, "
11725                            + ((requirer == null) ? "[caller]" : requirer)
11726                            + " requires " + requiredInstructionSet + " whereas " + ps
11727                            + " requires " + instructionSet;
11728                    Slog.w(TAG, errorMessage);
11729                }
11730
11731                if (requiredInstructionSet == null) {
11732                    requiredInstructionSet = instructionSet;
11733                    requirer = ps;
11734                }
11735            }
11736        }
11737
11738        if (requiredInstructionSet != null) {
11739            String adjustedAbi;
11740            if (requirer != null) {
11741                // requirer != null implies that either scannedPackage was null or that scannedPackage
11742                // did not require an ABI, in which case we have to adjust scannedPackage to match
11743                // the ABI of the set (which is the same as requirer's ABI)
11744                adjustedAbi = requirer.primaryCpuAbiString;
11745                if (scannedPackage != null) {
11746                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11747                }
11748            } else {
11749                // requirer == null implies that we're updating all ABIs in the set to
11750                // match scannedPackage.
11751                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11752            }
11753
11754            for (PackageSetting ps : packagesForUser) {
11755                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11756                    if (ps.primaryCpuAbiString != null) {
11757                        continue;
11758                    }
11759
11760                    ps.primaryCpuAbiString = adjustedAbi;
11761                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11762                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11763                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11764                        if (DEBUG_ABI_SELECTION) {
11765                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11766                                    + " (requirer="
11767                                    + (requirer != null ? requirer.pkg : "null")
11768                                    + ", scannedPackage="
11769                                    + (scannedPackage != null ? scannedPackage : "null")
11770                                    + ")");
11771                        }
11772                        if (changedAbiCodePath == null) {
11773                            changedAbiCodePath = new ArrayList<>();
11774                        }
11775                        changedAbiCodePath.add(ps.codePathString);
11776                    }
11777                }
11778            }
11779        }
11780        return changedAbiCodePath;
11781    }
11782
11783    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11784        synchronized (mPackages) {
11785            mResolverReplaced = true;
11786            // Set up information for custom user intent resolution activity.
11787            mResolveActivity.applicationInfo = pkg.applicationInfo;
11788            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11789            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11790            mResolveActivity.processName = pkg.applicationInfo.packageName;
11791            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11792            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11793                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11794            mResolveActivity.theme = 0;
11795            mResolveActivity.exported = true;
11796            mResolveActivity.enabled = true;
11797            mResolveInfo.activityInfo = mResolveActivity;
11798            mResolveInfo.priority = 0;
11799            mResolveInfo.preferredOrder = 0;
11800            mResolveInfo.match = 0;
11801            mResolveComponentName = mCustomResolverComponentName;
11802            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11803                    mResolveComponentName);
11804        }
11805    }
11806
11807    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11808        if (installerActivity == null) {
11809            if (DEBUG_INSTANT) {
11810                Slog.d(TAG, "Clear ephemeral installer activity");
11811            }
11812            mInstantAppInstallerActivity = null;
11813            return;
11814        }
11815
11816        if (DEBUG_INSTANT) {
11817            Slog.d(TAG, "Set ephemeral installer activity: "
11818                    + installerActivity.getComponentName());
11819        }
11820        // Set up information for ephemeral installer activity
11821        mInstantAppInstallerActivity = installerActivity;
11822        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11823                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11824        mInstantAppInstallerActivity.exported = true;
11825        mInstantAppInstallerActivity.enabled = true;
11826        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11827        mInstantAppInstallerInfo.priority = 1;
11828        mInstantAppInstallerInfo.preferredOrder = 1;
11829        mInstantAppInstallerInfo.isDefault = true;
11830        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11831                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11832    }
11833
11834    private static String calculateBundledApkRoot(final String codePathString) {
11835        final File codePath = new File(codePathString);
11836        final File codeRoot;
11837        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11838            codeRoot = Environment.getRootDirectory();
11839        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11840            codeRoot = Environment.getOemDirectory();
11841        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11842            codeRoot = Environment.getVendorDirectory();
11843        } else if (FileUtils.contains(Environment.getOdmDirectory(), codePath)) {
11844            codeRoot = Environment.getOdmDirectory();
11845        } else if (FileUtils.contains(Environment.getProductDirectory(), codePath)) {
11846            codeRoot = Environment.getProductDirectory();
11847        } else {
11848            // Unrecognized code path; take its top real segment as the apk root:
11849            // e.g. /something/app/blah.apk => /something
11850            try {
11851                File f = codePath.getCanonicalFile();
11852                File parent = f.getParentFile();    // non-null because codePath is a file
11853                File tmp;
11854                while ((tmp = parent.getParentFile()) != null) {
11855                    f = parent;
11856                    parent = tmp;
11857                }
11858                codeRoot = f;
11859                Slog.w(TAG, "Unrecognized code path "
11860                        + codePath + " - using " + codeRoot);
11861            } catch (IOException e) {
11862                // Can't canonicalize the code path -- shenanigans?
11863                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11864                return Environment.getRootDirectory().getPath();
11865            }
11866        }
11867        return codeRoot.getPath();
11868    }
11869
11870    /**
11871     * Derive and set the location of native libraries for the given package,
11872     * which varies depending on where and how the package was installed.
11873     */
11874    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11875        final ApplicationInfo info = pkg.applicationInfo;
11876        final String codePath = pkg.codePath;
11877        final File codeFile = new File(codePath);
11878        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11879        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11880
11881        info.nativeLibraryRootDir = null;
11882        info.nativeLibraryRootRequiresIsa = false;
11883        info.nativeLibraryDir = null;
11884        info.secondaryNativeLibraryDir = null;
11885
11886        if (isApkFile(codeFile)) {
11887            // Monolithic install
11888            if (bundledApp) {
11889                // If "/system/lib64/apkname" exists, assume that is the per-package
11890                // native library directory to use; otherwise use "/system/lib/apkname".
11891                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11892                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11893                        getPrimaryInstructionSet(info));
11894
11895                // This is a bundled system app so choose the path based on the ABI.
11896                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11897                // is just the default path.
11898                final String apkName = deriveCodePathName(codePath);
11899                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11900                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11901                        apkName).getAbsolutePath();
11902
11903                if (info.secondaryCpuAbi != null) {
11904                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11905                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11906                            secondaryLibDir, apkName).getAbsolutePath();
11907                }
11908            } else if (asecApp) {
11909                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11910                        .getAbsolutePath();
11911            } else {
11912                final String apkName = deriveCodePathName(codePath);
11913                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11914                        .getAbsolutePath();
11915            }
11916
11917            info.nativeLibraryRootRequiresIsa = false;
11918            info.nativeLibraryDir = info.nativeLibraryRootDir;
11919        } else {
11920            // Cluster install
11921            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11922            info.nativeLibraryRootRequiresIsa = true;
11923
11924            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11925                    getPrimaryInstructionSet(info)).getAbsolutePath();
11926
11927            if (info.secondaryCpuAbi != null) {
11928                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11929                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11930            }
11931        }
11932    }
11933
11934    /**
11935     * Calculate the abis and roots for a bundled app. These can uniquely
11936     * be determined from the contents of the system partition, i.e whether
11937     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11938     * of this information, and instead assume that the system was built
11939     * sensibly.
11940     */
11941    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11942                                           PackageSetting pkgSetting) {
11943        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11944
11945        // If "/system/lib64/apkname" exists, assume that is the per-package
11946        // native library directory to use; otherwise use "/system/lib/apkname".
11947        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11948        setBundledAppAbi(pkg, apkRoot, apkName);
11949        // pkgSetting might be null during rescan following uninstall of updates
11950        // to a bundled app, so accommodate that possibility.  The settings in
11951        // that case will be established later from the parsed package.
11952        //
11953        // If the settings aren't null, sync them up with what we've just derived.
11954        // note that apkRoot isn't stored in the package settings.
11955        if (pkgSetting != null) {
11956            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11957            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11958        }
11959    }
11960
11961    /**
11962     * Deduces the ABI of a bundled app and sets the relevant fields on the
11963     * parsed pkg object.
11964     *
11965     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11966     *        under which system libraries are installed.
11967     * @param apkName the name of the installed package.
11968     */
11969    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11970        final File codeFile = new File(pkg.codePath);
11971
11972        final boolean has64BitLibs;
11973        final boolean has32BitLibs;
11974        if (isApkFile(codeFile)) {
11975            // Monolithic install
11976            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11977            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11978        } else {
11979            // Cluster install
11980            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11981            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11982                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11983                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11984                has64BitLibs = (new File(rootDir, isa)).exists();
11985            } else {
11986                has64BitLibs = false;
11987            }
11988            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11989                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11990                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11991                has32BitLibs = (new File(rootDir, isa)).exists();
11992            } else {
11993                has32BitLibs = false;
11994            }
11995        }
11996
11997        if (has64BitLibs && !has32BitLibs) {
11998            // The package has 64 bit libs, but not 32 bit libs. Its primary
11999            // ABI should be 64 bit. We can safely assume here that the bundled
12000            // native libraries correspond to the most preferred ABI in the list.
12001
12002            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12003            pkg.applicationInfo.secondaryCpuAbi = null;
12004        } else if (has32BitLibs && !has64BitLibs) {
12005            // The package has 32 bit libs but not 64 bit libs. Its primary
12006            // ABI should be 32 bit.
12007
12008            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12009            pkg.applicationInfo.secondaryCpuAbi = null;
12010        } else if (has32BitLibs && has64BitLibs) {
12011            // The application has both 64 and 32 bit bundled libraries. We check
12012            // here that the app declares multiArch support, and warn if it doesn't.
12013            //
12014            // We will be lenient here and record both ABIs. The primary will be the
12015            // ABI that's higher on the list, i.e, a device that's configured to prefer
12016            // 64 bit apps will see a 64 bit primary ABI,
12017
12018            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12019                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12020            }
12021
12022            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12023                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12024                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12025            } else {
12026                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12027                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12028            }
12029        } else {
12030            pkg.applicationInfo.primaryCpuAbi = null;
12031            pkg.applicationInfo.secondaryCpuAbi = null;
12032        }
12033    }
12034
12035    private void killApplication(String pkgName, int appId, String reason) {
12036        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12037    }
12038
12039    private void killApplication(String pkgName, int appId, int userId, String reason) {
12040        // Request the ActivityManager to kill the process(only for existing packages)
12041        // so that we do not end up in a confused state while the user is still using the older
12042        // version of the application while the new one gets installed.
12043        final long token = Binder.clearCallingIdentity();
12044        try {
12045            IActivityManager am = ActivityManager.getService();
12046            if (am != null) {
12047                try {
12048                    am.killApplication(pkgName, appId, userId, reason);
12049                } catch (RemoteException e) {
12050                }
12051            }
12052        } finally {
12053            Binder.restoreCallingIdentity(token);
12054        }
12055    }
12056
12057    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12058        // Remove the parent package setting
12059        PackageSetting ps = (PackageSetting) pkg.mExtras;
12060        if (ps != null) {
12061            removePackageLI(ps, chatty);
12062        }
12063        // Remove the child package setting
12064        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12065        for (int i = 0; i < childCount; i++) {
12066            PackageParser.Package childPkg = pkg.childPackages.get(i);
12067            ps = (PackageSetting) childPkg.mExtras;
12068            if (ps != null) {
12069                removePackageLI(ps, chatty);
12070            }
12071        }
12072    }
12073
12074    void removePackageLI(PackageSetting ps, boolean chatty) {
12075        if (DEBUG_INSTALL) {
12076            if (chatty)
12077                Log.d(TAG, "Removing package " + ps.name);
12078        }
12079
12080        // writer
12081        synchronized (mPackages) {
12082            mPackages.remove(ps.name);
12083            final PackageParser.Package pkg = ps.pkg;
12084            if (pkg != null) {
12085                cleanPackageDataStructuresLILPw(pkg, chatty);
12086            }
12087        }
12088    }
12089
12090    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12091        if (DEBUG_INSTALL) {
12092            if (chatty)
12093                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12094        }
12095
12096        // writer
12097        synchronized (mPackages) {
12098            // Remove the parent package
12099            mPackages.remove(pkg.applicationInfo.packageName);
12100            cleanPackageDataStructuresLILPw(pkg, chatty);
12101
12102            // Remove the child packages
12103            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12104            for (int i = 0; i < childCount; i++) {
12105                PackageParser.Package childPkg = pkg.childPackages.get(i);
12106                mPackages.remove(childPkg.applicationInfo.packageName);
12107                cleanPackageDataStructuresLILPw(childPkg, chatty);
12108            }
12109        }
12110    }
12111
12112    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12113        int N = pkg.providers.size();
12114        StringBuilder r = null;
12115        int i;
12116        for (i=0; i<N; i++) {
12117            PackageParser.Provider p = pkg.providers.get(i);
12118            mProviders.removeProvider(p);
12119            if (p.info.authority == null) {
12120
12121                /* There was another ContentProvider with this authority when
12122                 * this app was installed so this authority is null,
12123                 * Ignore it as we don't have to unregister the provider.
12124                 */
12125                continue;
12126            }
12127            String names[] = p.info.authority.split(";");
12128            for (int j = 0; j < names.length; j++) {
12129                if (mProvidersByAuthority.get(names[j]) == p) {
12130                    mProvidersByAuthority.remove(names[j]);
12131                    if (DEBUG_REMOVE) {
12132                        if (chatty)
12133                            Log.d(TAG, "Unregistered content provider: " + names[j]
12134                                    + ", className = " + p.info.name + ", isSyncable = "
12135                                    + p.info.isSyncable);
12136                    }
12137                }
12138            }
12139            if (DEBUG_REMOVE && chatty) {
12140                if (r == null) {
12141                    r = new StringBuilder(256);
12142                } else {
12143                    r.append(' ');
12144                }
12145                r.append(p.info.name);
12146            }
12147        }
12148        if (r != null) {
12149            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12150        }
12151
12152        N = pkg.services.size();
12153        r = null;
12154        for (i=0; i<N; i++) {
12155            PackageParser.Service s = pkg.services.get(i);
12156            mServices.removeService(s);
12157            if (chatty) {
12158                if (r == null) {
12159                    r = new StringBuilder(256);
12160                } else {
12161                    r.append(' ');
12162                }
12163                r.append(s.info.name);
12164            }
12165        }
12166        if (r != null) {
12167            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12168        }
12169
12170        N = pkg.receivers.size();
12171        r = null;
12172        for (i=0; i<N; i++) {
12173            PackageParser.Activity a = pkg.receivers.get(i);
12174            mReceivers.removeActivity(a, "receiver");
12175            if (DEBUG_REMOVE && chatty) {
12176                if (r == null) {
12177                    r = new StringBuilder(256);
12178                } else {
12179                    r.append(' ');
12180                }
12181                r.append(a.info.name);
12182            }
12183        }
12184        if (r != null) {
12185            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12186        }
12187
12188        N = pkg.activities.size();
12189        r = null;
12190        for (i=0; i<N; i++) {
12191            PackageParser.Activity a = pkg.activities.get(i);
12192            mActivities.removeActivity(a, "activity");
12193            if (DEBUG_REMOVE && chatty) {
12194                if (r == null) {
12195                    r = new StringBuilder(256);
12196                } else {
12197                    r.append(' ');
12198                }
12199                r.append(a.info.name);
12200            }
12201        }
12202        if (r != null) {
12203            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12204        }
12205
12206        mPermissionManager.removeAllPermissions(pkg, chatty);
12207
12208        N = pkg.instrumentation.size();
12209        r = null;
12210        for (i=0; i<N; i++) {
12211            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12212            mInstrumentation.remove(a.getComponentName());
12213            if (DEBUG_REMOVE && chatty) {
12214                if (r == null) {
12215                    r = new StringBuilder(256);
12216                } else {
12217                    r.append(' ');
12218                }
12219                r.append(a.info.name);
12220            }
12221        }
12222        if (r != null) {
12223            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12224        }
12225
12226        r = null;
12227        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12228            // Only system apps can hold shared libraries.
12229            if (pkg.libraryNames != null) {
12230                for (i = 0; i < pkg.libraryNames.size(); i++) {
12231                    String name = pkg.libraryNames.get(i);
12232                    if (removeSharedLibraryLPw(name, 0)) {
12233                        if (DEBUG_REMOVE && chatty) {
12234                            if (r == null) {
12235                                r = new StringBuilder(256);
12236                            } else {
12237                                r.append(' ');
12238                            }
12239                            r.append(name);
12240                        }
12241                    }
12242                }
12243            }
12244        }
12245
12246        r = null;
12247
12248        // Any package can hold static shared libraries.
12249        if (pkg.staticSharedLibName != null) {
12250            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12251                if (DEBUG_REMOVE && chatty) {
12252                    if (r == null) {
12253                        r = new StringBuilder(256);
12254                    } else {
12255                        r.append(' ');
12256                    }
12257                    r.append(pkg.staticSharedLibName);
12258                }
12259            }
12260        }
12261
12262        if (r != null) {
12263            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12264        }
12265    }
12266
12267
12268    final class ActivityIntentResolver
12269            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12270        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12271                boolean defaultOnly, int userId) {
12272            if (!sUserManager.exists(userId)) return null;
12273            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12274            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12275        }
12276
12277        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12278                int userId) {
12279            if (!sUserManager.exists(userId)) return null;
12280            mFlags = flags;
12281            return super.queryIntent(intent, resolvedType,
12282                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12283                    userId);
12284        }
12285
12286        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12287                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12288            if (!sUserManager.exists(userId)) return null;
12289            if (packageActivities == null) {
12290                return null;
12291            }
12292            mFlags = flags;
12293            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12294            final int N = packageActivities.size();
12295            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12296                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12297
12298            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12299            for (int i = 0; i < N; ++i) {
12300                intentFilters = packageActivities.get(i).intents;
12301                if (intentFilters != null && intentFilters.size() > 0) {
12302                    PackageParser.ActivityIntentInfo[] array =
12303                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12304                    intentFilters.toArray(array);
12305                    listCut.add(array);
12306                }
12307            }
12308            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12309        }
12310
12311        /**
12312         * Finds a privileged activity that matches the specified activity names.
12313         */
12314        private PackageParser.Activity findMatchingActivity(
12315                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12316            for (PackageParser.Activity sysActivity : activityList) {
12317                if (sysActivity.info.name.equals(activityInfo.name)) {
12318                    return sysActivity;
12319                }
12320                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12321                    return sysActivity;
12322                }
12323                if (sysActivity.info.targetActivity != null) {
12324                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12325                        return sysActivity;
12326                    }
12327                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12328                        return sysActivity;
12329                    }
12330                }
12331            }
12332            return null;
12333        }
12334
12335        public class IterGenerator<E> {
12336            public Iterator<E> generate(ActivityIntentInfo info) {
12337                return null;
12338            }
12339        }
12340
12341        public class ActionIterGenerator extends IterGenerator<String> {
12342            @Override
12343            public Iterator<String> generate(ActivityIntentInfo info) {
12344                return info.actionsIterator();
12345            }
12346        }
12347
12348        public class CategoriesIterGenerator extends IterGenerator<String> {
12349            @Override
12350            public Iterator<String> generate(ActivityIntentInfo info) {
12351                return info.categoriesIterator();
12352            }
12353        }
12354
12355        public class SchemesIterGenerator extends IterGenerator<String> {
12356            @Override
12357            public Iterator<String> generate(ActivityIntentInfo info) {
12358                return info.schemesIterator();
12359            }
12360        }
12361
12362        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12363            @Override
12364            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12365                return info.authoritiesIterator();
12366            }
12367        }
12368
12369        /**
12370         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12371         * MODIFIED. Do not pass in a list that should not be changed.
12372         */
12373        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12374                IterGenerator<T> generator, Iterator<T> searchIterator) {
12375            // loop through the set of actions; every one must be found in the intent filter
12376            while (searchIterator.hasNext()) {
12377                // we must have at least one filter in the list to consider a match
12378                if (intentList.size() == 0) {
12379                    break;
12380                }
12381
12382                final T searchAction = searchIterator.next();
12383
12384                // loop through the set of intent filters
12385                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12386                while (intentIter.hasNext()) {
12387                    final ActivityIntentInfo intentInfo = intentIter.next();
12388                    boolean selectionFound = false;
12389
12390                    // loop through the intent filter's selection criteria; at least one
12391                    // of them must match the searched criteria
12392                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12393                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12394                        final T intentSelection = intentSelectionIter.next();
12395                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12396                            selectionFound = true;
12397                            break;
12398                        }
12399                    }
12400
12401                    // the selection criteria wasn't found in this filter's set; this filter
12402                    // is not a potential match
12403                    if (!selectionFound) {
12404                        intentIter.remove();
12405                    }
12406                }
12407            }
12408        }
12409
12410        private boolean isProtectedAction(ActivityIntentInfo filter) {
12411            final Iterator<String> actionsIter = filter.actionsIterator();
12412            while (actionsIter != null && actionsIter.hasNext()) {
12413                final String filterAction = actionsIter.next();
12414                if (PROTECTED_ACTIONS.contains(filterAction)) {
12415                    return true;
12416                }
12417            }
12418            return false;
12419        }
12420
12421        /**
12422         * Adjusts the priority of the given intent filter according to policy.
12423         * <p>
12424         * <ul>
12425         * <li>The priority for non privileged applications is capped to '0'</li>
12426         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12427         * <li>The priority for unbundled updates to privileged applications is capped to the
12428         *      priority defined on the system partition</li>
12429         * </ul>
12430         * <p>
12431         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12432         * allowed to obtain any priority on any action.
12433         */
12434        private void adjustPriority(
12435                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12436            // nothing to do; priority is fine as-is
12437            if (intent.getPriority() <= 0) {
12438                return;
12439            }
12440
12441            final ActivityInfo activityInfo = intent.activity.info;
12442            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12443
12444            final boolean privilegedApp =
12445                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12446            if (!privilegedApp) {
12447                // non-privileged applications can never define a priority >0
12448                if (DEBUG_FILTERS) {
12449                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12450                            + " package: " + applicationInfo.packageName
12451                            + " activity: " + intent.activity.className
12452                            + " origPrio: " + intent.getPriority());
12453                }
12454                intent.setPriority(0);
12455                return;
12456            }
12457
12458            if (systemActivities == null) {
12459                // the system package is not disabled; we're parsing the system partition
12460                if (isProtectedAction(intent)) {
12461                    if (mDeferProtectedFilters) {
12462                        // We can't deal with these just yet. No component should ever obtain a
12463                        // >0 priority for a protected actions, with ONE exception -- the setup
12464                        // wizard. The setup wizard, however, cannot be known until we're able to
12465                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12466                        // until all intent filters have been processed. Chicken, meet egg.
12467                        // Let the filter temporarily have a high priority and rectify the
12468                        // priorities after all system packages have been scanned.
12469                        mProtectedFilters.add(intent);
12470                        if (DEBUG_FILTERS) {
12471                            Slog.i(TAG, "Protected action; save for later;"
12472                                    + " package: " + applicationInfo.packageName
12473                                    + " activity: " + intent.activity.className
12474                                    + " origPrio: " + intent.getPriority());
12475                        }
12476                        return;
12477                    } else {
12478                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12479                            Slog.i(TAG, "No setup wizard;"
12480                                + " All protected intents capped to priority 0");
12481                        }
12482                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12483                            if (DEBUG_FILTERS) {
12484                                Slog.i(TAG, "Found setup wizard;"
12485                                    + " allow priority " + intent.getPriority() + ";"
12486                                    + " package: " + intent.activity.info.packageName
12487                                    + " activity: " + intent.activity.className
12488                                    + " priority: " + intent.getPriority());
12489                            }
12490                            // setup wizard gets whatever it wants
12491                            return;
12492                        }
12493                        if (DEBUG_FILTERS) {
12494                            Slog.i(TAG, "Protected action; cap priority to 0;"
12495                                    + " package: " + intent.activity.info.packageName
12496                                    + " activity: " + intent.activity.className
12497                                    + " origPrio: " + intent.getPriority());
12498                        }
12499                        intent.setPriority(0);
12500                        return;
12501                    }
12502                }
12503                // privileged apps on the system image get whatever priority they request
12504                return;
12505            }
12506
12507            // privileged app unbundled update ... try to find the same activity
12508            final PackageParser.Activity foundActivity =
12509                    findMatchingActivity(systemActivities, activityInfo);
12510            if (foundActivity == null) {
12511                // this is a new activity; it cannot obtain >0 priority
12512                if (DEBUG_FILTERS) {
12513                    Slog.i(TAG, "New activity; cap priority to 0;"
12514                            + " package: " + applicationInfo.packageName
12515                            + " activity: " + intent.activity.className
12516                            + " origPrio: " + intent.getPriority());
12517                }
12518                intent.setPriority(0);
12519                return;
12520            }
12521
12522            // found activity, now check for filter equivalence
12523
12524            // a shallow copy is enough; we modify the list, not its contents
12525            final List<ActivityIntentInfo> intentListCopy =
12526                    new ArrayList<>(foundActivity.intents);
12527            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12528
12529            // find matching action subsets
12530            final Iterator<String> actionsIterator = intent.actionsIterator();
12531            if (actionsIterator != null) {
12532                getIntentListSubset(
12533                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12534                if (intentListCopy.size() == 0) {
12535                    // no more intents to match; we're not equivalent
12536                    if (DEBUG_FILTERS) {
12537                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12538                                + " package: " + applicationInfo.packageName
12539                                + " activity: " + intent.activity.className
12540                                + " origPrio: " + intent.getPriority());
12541                    }
12542                    intent.setPriority(0);
12543                    return;
12544                }
12545            }
12546
12547            // find matching category subsets
12548            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12549            if (categoriesIterator != null) {
12550                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12551                        categoriesIterator);
12552                if (intentListCopy.size() == 0) {
12553                    // no more intents to match; we're not equivalent
12554                    if (DEBUG_FILTERS) {
12555                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12556                                + " package: " + applicationInfo.packageName
12557                                + " activity: " + intent.activity.className
12558                                + " origPrio: " + intent.getPriority());
12559                    }
12560                    intent.setPriority(0);
12561                    return;
12562                }
12563            }
12564
12565            // find matching schemes subsets
12566            final Iterator<String> schemesIterator = intent.schemesIterator();
12567            if (schemesIterator != null) {
12568                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12569                        schemesIterator);
12570                if (intentListCopy.size() == 0) {
12571                    // no more intents to match; we're not equivalent
12572                    if (DEBUG_FILTERS) {
12573                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12574                                + " package: " + applicationInfo.packageName
12575                                + " activity: " + intent.activity.className
12576                                + " origPrio: " + intent.getPriority());
12577                    }
12578                    intent.setPriority(0);
12579                    return;
12580                }
12581            }
12582
12583            // find matching authorities subsets
12584            final Iterator<IntentFilter.AuthorityEntry>
12585                    authoritiesIterator = intent.authoritiesIterator();
12586            if (authoritiesIterator != null) {
12587                getIntentListSubset(intentListCopy,
12588                        new AuthoritiesIterGenerator(),
12589                        authoritiesIterator);
12590                if (intentListCopy.size() == 0) {
12591                    // no more intents to match; we're not equivalent
12592                    if (DEBUG_FILTERS) {
12593                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12594                                + " package: " + applicationInfo.packageName
12595                                + " activity: " + intent.activity.className
12596                                + " origPrio: " + intent.getPriority());
12597                    }
12598                    intent.setPriority(0);
12599                    return;
12600                }
12601            }
12602
12603            // we found matching filter(s); app gets the max priority of all intents
12604            int cappedPriority = 0;
12605            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12606                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12607            }
12608            if (intent.getPriority() > cappedPriority) {
12609                if (DEBUG_FILTERS) {
12610                    Slog.i(TAG, "Found matching filter(s);"
12611                            + " cap priority to " + cappedPriority + ";"
12612                            + " package: " + applicationInfo.packageName
12613                            + " activity: " + intent.activity.className
12614                            + " origPrio: " + intent.getPriority());
12615                }
12616                intent.setPriority(cappedPriority);
12617                return;
12618            }
12619            // all this for nothing; the requested priority was <= what was on the system
12620        }
12621
12622        public final void addActivity(PackageParser.Activity a, String type) {
12623            mActivities.put(a.getComponentName(), a);
12624            if (DEBUG_SHOW_INFO)
12625                Log.v(
12626                TAG, "  " + type + " " +
12627                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12628            if (DEBUG_SHOW_INFO)
12629                Log.v(TAG, "    Class=" + a.info.name);
12630            final int NI = a.intents.size();
12631            for (int j=0; j<NI; j++) {
12632                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12633                if ("activity".equals(type)) {
12634                    final PackageSetting ps =
12635                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12636                    final List<PackageParser.Activity> systemActivities =
12637                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12638                    adjustPriority(systemActivities, intent);
12639                }
12640                if (DEBUG_SHOW_INFO) {
12641                    Log.v(TAG, "    IntentFilter:");
12642                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12643                }
12644                if (!intent.debugCheck()) {
12645                    Log.w(TAG, "==> For Activity " + a.info.name);
12646                }
12647                addFilter(intent);
12648            }
12649        }
12650
12651        public final void removeActivity(PackageParser.Activity a, String type) {
12652            mActivities.remove(a.getComponentName());
12653            if (DEBUG_SHOW_INFO) {
12654                Log.v(TAG, "  " + type + " "
12655                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12656                                : a.info.name) + ":");
12657                Log.v(TAG, "    Class=" + a.info.name);
12658            }
12659            final int NI = a.intents.size();
12660            for (int j=0; j<NI; j++) {
12661                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12662                if (DEBUG_SHOW_INFO) {
12663                    Log.v(TAG, "    IntentFilter:");
12664                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12665                }
12666                removeFilter(intent);
12667            }
12668        }
12669
12670        @Override
12671        protected boolean allowFilterResult(
12672                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12673            ActivityInfo filterAi = filter.activity.info;
12674            for (int i=dest.size()-1; i>=0; i--) {
12675                ActivityInfo destAi = dest.get(i).activityInfo;
12676                if (destAi.name == filterAi.name
12677                        && destAi.packageName == filterAi.packageName) {
12678                    return false;
12679                }
12680            }
12681            return true;
12682        }
12683
12684        @Override
12685        protected ActivityIntentInfo[] newArray(int size) {
12686            return new ActivityIntentInfo[size];
12687        }
12688
12689        @Override
12690        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12691            if (!sUserManager.exists(userId)) return true;
12692            PackageParser.Package p = filter.activity.owner;
12693            if (p != null) {
12694                PackageSetting ps = (PackageSetting)p.mExtras;
12695                if (ps != null) {
12696                    // System apps are never considered stopped for purposes of
12697                    // filtering, because there may be no way for the user to
12698                    // actually re-launch them.
12699                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12700                            && ps.getStopped(userId);
12701                }
12702            }
12703            return false;
12704        }
12705
12706        @Override
12707        protected boolean isPackageForFilter(String packageName,
12708                PackageParser.ActivityIntentInfo info) {
12709            return packageName.equals(info.activity.owner.packageName);
12710        }
12711
12712        @Override
12713        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12714                int match, int userId) {
12715            if (!sUserManager.exists(userId)) return null;
12716            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12717                return null;
12718            }
12719            final PackageParser.Activity activity = info.activity;
12720            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12721            if (ps == null) {
12722                return null;
12723            }
12724            final PackageUserState userState = ps.readUserState(userId);
12725            ActivityInfo ai =
12726                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
12727            if (ai == null) {
12728                return null;
12729            }
12730            final boolean matchExplicitlyVisibleOnly =
12731                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12732            final boolean matchVisibleToInstantApp =
12733                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12734            final boolean componentVisible =
12735                    matchVisibleToInstantApp
12736                    && info.isVisibleToInstantApp()
12737                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12738            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12739            // throw out filters that aren't visible to ephemeral apps
12740            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12741                return null;
12742            }
12743            // throw out instant app filters if we're not explicitly requesting them
12744            if (!matchInstantApp && userState.instantApp) {
12745                return null;
12746            }
12747            // throw out instant app filters if updates are available; will trigger
12748            // instant app resolution
12749            if (userState.instantApp && ps.isUpdateAvailable()) {
12750                return null;
12751            }
12752            final ResolveInfo res = new ResolveInfo();
12753            res.activityInfo = ai;
12754            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12755                res.filter = info;
12756            }
12757            if (info != null) {
12758                res.handleAllWebDataURI = info.handleAllWebDataURI();
12759            }
12760            res.priority = info.getPriority();
12761            res.preferredOrder = activity.owner.mPreferredOrder;
12762            //System.out.println("Result: " + res.activityInfo.className +
12763            //                   " = " + res.priority);
12764            res.match = match;
12765            res.isDefault = info.hasDefault;
12766            res.labelRes = info.labelRes;
12767            res.nonLocalizedLabel = info.nonLocalizedLabel;
12768            if (userNeedsBadging(userId)) {
12769                res.noResourceId = true;
12770            } else {
12771                res.icon = info.icon;
12772            }
12773            res.iconResourceId = info.icon;
12774            res.system = res.activityInfo.applicationInfo.isSystemApp();
12775            res.isInstantAppAvailable = userState.instantApp;
12776            return res;
12777        }
12778
12779        @Override
12780        protected void sortResults(List<ResolveInfo> results) {
12781            Collections.sort(results, mResolvePrioritySorter);
12782        }
12783
12784        @Override
12785        protected void dumpFilter(PrintWriter out, String prefix,
12786                PackageParser.ActivityIntentInfo filter) {
12787            out.print(prefix); out.print(
12788                    Integer.toHexString(System.identityHashCode(filter.activity)));
12789                    out.print(' ');
12790                    filter.activity.printComponentShortName(out);
12791                    out.print(" filter ");
12792                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12793        }
12794
12795        @Override
12796        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12797            return filter.activity;
12798        }
12799
12800        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12801            PackageParser.Activity activity = (PackageParser.Activity)label;
12802            out.print(prefix); out.print(
12803                    Integer.toHexString(System.identityHashCode(activity)));
12804                    out.print(' ');
12805                    activity.printComponentShortName(out);
12806            if (count > 1) {
12807                out.print(" ("); out.print(count); out.print(" filters)");
12808            }
12809            out.println();
12810        }
12811
12812        // Keys are String (activity class name), values are Activity.
12813        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12814                = new ArrayMap<ComponentName, PackageParser.Activity>();
12815        private int mFlags;
12816    }
12817
12818    private final class ServiceIntentResolver
12819            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12820        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12821                boolean defaultOnly, int userId) {
12822            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12823            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12824        }
12825
12826        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12827                int userId) {
12828            if (!sUserManager.exists(userId)) return null;
12829            mFlags = flags;
12830            return super.queryIntent(intent, resolvedType,
12831                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12832                    userId);
12833        }
12834
12835        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12836                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12837            if (!sUserManager.exists(userId)) return null;
12838            if (packageServices == null) {
12839                return null;
12840            }
12841            mFlags = flags;
12842            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12843            final int N = packageServices.size();
12844            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12845                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12846
12847            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12848            for (int i = 0; i < N; ++i) {
12849                intentFilters = packageServices.get(i).intents;
12850                if (intentFilters != null && intentFilters.size() > 0) {
12851                    PackageParser.ServiceIntentInfo[] array =
12852                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12853                    intentFilters.toArray(array);
12854                    listCut.add(array);
12855                }
12856            }
12857            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12858        }
12859
12860        public final void addService(PackageParser.Service s) {
12861            mServices.put(s.getComponentName(), s);
12862            if (DEBUG_SHOW_INFO) {
12863                Log.v(TAG, "  "
12864                        + (s.info.nonLocalizedLabel != null
12865                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12866                Log.v(TAG, "    Class=" + s.info.name);
12867            }
12868            final int NI = s.intents.size();
12869            int j;
12870            for (j=0; j<NI; j++) {
12871                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12872                if (DEBUG_SHOW_INFO) {
12873                    Log.v(TAG, "    IntentFilter:");
12874                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12875                }
12876                if (!intent.debugCheck()) {
12877                    Log.w(TAG, "==> For Service " + s.info.name);
12878                }
12879                addFilter(intent);
12880            }
12881        }
12882
12883        public final void removeService(PackageParser.Service s) {
12884            mServices.remove(s.getComponentName());
12885            if (DEBUG_SHOW_INFO) {
12886                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12887                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12888                Log.v(TAG, "    Class=" + s.info.name);
12889            }
12890            final int NI = s.intents.size();
12891            int j;
12892            for (j=0; j<NI; j++) {
12893                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12894                if (DEBUG_SHOW_INFO) {
12895                    Log.v(TAG, "    IntentFilter:");
12896                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12897                }
12898                removeFilter(intent);
12899            }
12900        }
12901
12902        @Override
12903        protected boolean allowFilterResult(
12904                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12905            ServiceInfo filterSi = filter.service.info;
12906            for (int i=dest.size()-1; i>=0; i--) {
12907                ServiceInfo destAi = dest.get(i).serviceInfo;
12908                if (destAi.name == filterSi.name
12909                        && destAi.packageName == filterSi.packageName) {
12910                    return false;
12911                }
12912            }
12913            return true;
12914        }
12915
12916        @Override
12917        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12918            return new PackageParser.ServiceIntentInfo[size];
12919        }
12920
12921        @Override
12922        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12923            if (!sUserManager.exists(userId)) return true;
12924            PackageParser.Package p = filter.service.owner;
12925            if (p != null) {
12926                PackageSetting ps = (PackageSetting)p.mExtras;
12927                if (ps != null) {
12928                    // System apps are never considered stopped for purposes of
12929                    // filtering, because there may be no way for the user to
12930                    // actually re-launch them.
12931                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12932                            && ps.getStopped(userId);
12933                }
12934            }
12935            return false;
12936        }
12937
12938        @Override
12939        protected boolean isPackageForFilter(String packageName,
12940                PackageParser.ServiceIntentInfo info) {
12941            return packageName.equals(info.service.owner.packageName);
12942        }
12943
12944        @Override
12945        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12946                int match, int userId) {
12947            if (!sUserManager.exists(userId)) return null;
12948            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12949            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12950                return null;
12951            }
12952            final PackageParser.Service service = info.service;
12953            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12954            if (ps == null) {
12955                return null;
12956            }
12957            final PackageUserState userState = ps.readUserState(userId);
12958            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12959                    userState, userId);
12960            if (si == null) {
12961                return null;
12962            }
12963            final boolean matchVisibleToInstantApp =
12964                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12965            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12966            // throw out filters that aren't visible to ephemeral apps
12967            if (matchVisibleToInstantApp
12968                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12969                return null;
12970            }
12971            // throw out ephemeral filters if we're not explicitly requesting them
12972            if (!isInstantApp && userState.instantApp) {
12973                return null;
12974            }
12975            // throw out instant app filters if updates are available; will trigger
12976            // instant app resolution
12977            if (userState.instantApp && ps.isUpdateAvailable()) {
12978                return null;
12979            }
12980            final ResolveInfo res = new ResolveInfo();
12981            res.serviceInfo = si;
12982            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12983                res.filter = filter;
12984            }
12985            res.priority = info.getPriority();
12986            res.preferredOrder = service.owner.mPreferredOrder;
12987            res.match = match;
12988            res.isDefault = info.hasDefault;
12989            res.labelRes = info.labelRes;
12990            res.nonLocalizedLabel = info.nonLocalizedLabel;
12991            res.icon = info.icon;
12992            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12993            return res;
12994        }
12995
12996        @Override
12997        protected void sortResults(List<ResolveInfo> results) {
12998            Collections.sort(results, mResolvePrioritySorter);
12999        }
13000
13001        @Override
13002        protected void dumpFilter(PrintWriter out, String prefix,
13003                PackageParser.ServiceIntentInfo filter) {
13004            out.print(prefix); out.print(
13005                    Integer.toHexString(System.identityHashCode(filter.service)));
13006                    out.print(' ');
13007                    filter.service.printComponentShortName(out);
13008                    out.print(" filter ");
13009                    out.print(Integer.toHexString(System.identityHashCode(filter)));
13010                    if (filter.service.info.permission != null) {
13011                        out.print(" permission "); out.println(filter.service.info.permission);
13012                    } else {
13013                        out.println();
13014                    }
13015        }
13016
13017        @Override
13018        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13019            return filter.service;
13020        }
13021
13022        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13023            PackageParser.Service service = (PackageParser.Service)label;
13024            out.print(prefix); out.print(
13025                    Integer.toHexString(System.identityHashCode(service)));
13026                    out.print(' ');
13027                    service.printComponentShortName(out);
13028            if (count > 1) {
13029                out.print(" ("); out.print(count); out.print(" filters)");
13030            }
13031            out.println();
13032        }
13033
13034//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13035//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13036//            final List<ResolveInfo> retList = Lists.newArrayList();
13037//            while (i.hasNext()) {
13038//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13039//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13040//                    retList.add(resolveInfo);
13041//                }
13042//            }
13043//            return retList;
13044//        }
13045
13046        // Keys are String (activity class name), values are Activity.
13047        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13048                = new ArrayMap<ComponentName, PackageParser.Service>();
13049        private int mFlags;
13050    }
13051
13052    private final class ProviderIntentResolver
13053            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13054        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13055                boolean defaultOnly, int userId) {
13056            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13057            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13058        }
13059
13060        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13061                int userId) {
13062            if (!sUserManager.exists(userId))
13063                return null;
13064            mFlags = flags;
13065            return super.queryIntent(intent, resolvedType,
13066                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13067                    userId);
13068        }
13069
13070        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13071                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13072            if (!sUserManager.exists(userId))
13073                return null;
13074            if (packageProviders == null) {
13075                return null;
13076            }
13077            mFlags = flags;
13078            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13079            final int N = packageProviders.size();
13080            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13081                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13082
13083            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13084            for (int i = 0; i < N; ++i) {
13085                intentFilters = packageProviders.get(i).intents;
13086                if (intentFilters != null && intentFilters.size() > 0) {
13087                    PackageParser.ProviderIntentInfo[] array =
13088                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13089                    intentFilters.toArray(array);
13090                    listCut.add(array);
13091                }
13092            }
13093            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13094        }
13095
13096        public final void addProvider(PackageParser.Provider p) {
13097            if (mProviders.containsKey(p.getComponentName())) {
13098                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13099                return;
13100            }
13101
13102            mProviders.put(p.getComponentName(), p);
13103            if (DEBUG_SHOW_INFO) {
13104                Log.v(TAG, "  "
13105                        + (p.info.nonLocalizedLabel != null
13106                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13107                Log.v(TAG, "    Class=" + p.info.name);
13108            }
13109            final int NI = p.intents.size();
13110            int j;
13111            for (j = 0; j < NI; j++) {
13112                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13113                if (DEBUG_SHOW_INFO) {
13114                    Log.v(TAG, "    IntentFilter:");
13115                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13116                }
13117                if (!intent.debugCheck()) {
13118                    Log.w(TAG, "==> For Provider " + p.info.name);
13119                }
13120                addFilter(intent);
13121            }
13122        }
13123
13124        public final void removeProvider(PackageParser.Provider p) {
13125            mProviders.remove(p.getComponentName());
13126            if (DEBUG_SHOW_INFO) {
13127                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13128                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13129                Log.v(TAG, "    Class=" + p.info.name);
13130            }
13131            final int NI = p.intents.size();
13132            int j;
13133            for (j = 0; j < NI; j++) {
13134                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13135                if (DEBUG_SHOW_INFO) {
13136                    Log.v(TAG, "    IntentFilter:");
13137                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13138                }
13139                removeFilter(intent);
13140            }
13141        }
13142
13143        @Override
13144        protected boolean allowFilterResult(
13145                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13146            ProviderInfo filterPi = filter.provider.info;
13147            for (int i = dest.size() - 1; i >= 0; i--) {
13148                ProviderInfo destPi = dest.get(i).providerInfo;
13149                if (destPi.name == filterPi.name
13150                        && destPi.packageName == filterPi.packageName) {
13151                    return false;
13152                }
13153            }
13154            return true;
13155        }
13156
13157        @Override
13158        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13159            return new PackageParser.ProviderIntentInfo[size];
13160        }
13161
13162        @Override
13163        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13164            if (!sUserManager.exists(userId))
13165                return true;
13166            PackageParser.Package p = filter.provider.owner;
13167            if (p != null) {
13168                PackageSetting ps = (PackageSetting) p.mExtras;
13169                if (ps != null) {
13170                    // System apps are never considered stopped for purposes of
13171                    // filtering, because there may be no way for the user to
13172                    // actually re-launch them.
13173                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13174                            && ps.getStopped(userId);
13175                }
13176            }
13177            return false;
13178        }
13179
13180        @Override
13181        protected boolean isPackageForFilter(String packageName,
13182                PackageParser.ProviderIntentInfo info) {
13183            return packageName.equals(info.provider.owner.packageName);
13184        }
13185
13186        @Override
13187        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13188                int match, int userId) {
13189            if (!sUserManager.exists(userId))
13190                return null;
13191            final PackageParser.ProviderIntentInfo info = filter;
13192            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13193                return null;
13194            }
13195            final PackageParser.Provider provider = info.provider;
13196            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13197            if (ps == null) {
13198                return null;
13199            }
13200            final PackageUserState userState = ps.readUserState(userId);
13201            final boolean matchVisibleToInstantApp =
13202                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13203            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13204            // throw out filters that aren't visible to instant applications
13205            if (matchVisibleToInstantApp
13206                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13207                return null;
13208            }
13209            // throw out instant application filters if we're not explicitly requesting them
13210            if (!isInstantApp && userState.instantApp) {
13211                return null;
13212            }
13213            // throw out instant application filters if updates are available; will trigger
13214            // instant application resolution
13215            if (userState.instantApp && ps.isUpdateAvailable()) {
13216                return null;
13217            }
13218            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13219                    userState, userId);
13220            if (pi == null) {
13221                return null;
13222            }
13223            final ResolveInfo res = new ResolveInfo();
13224            res.providerInfo = pi;
13225            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13226                res.filter = filter;
13227            }
13228            res.priority = info.getPriority();
13229            res.preferredOrder = provider.owner.mPreferredOrder;
13230            res.match = match;
13231            res.isDefault = info.hasDefault;
13232            res.labelRes = info.labelRes;
13233            res.nonLocalizedLabel = info.nonLocalizedLabel;
13234            res.icon = info.icon;
13235            res.system = res.providerInfo.applicationInfo.isSystemApp();
13236            return res;
13237        }
13238
13239        @Override
13240        protected void sortResults(List<ResolveInfo> results) {
13241            Collections.sort(results, mResolvePrioritySorter);
13242        }
13243
13244        @Override
13245        protected void dumpFilter(PrintWriter out, String prefix,
13246                PackageParser.ProviderIntentInfo filter) {
13247            out.print(prefix);
13248            out.print(
13249                    Integer.toHexString(System.identityHashCode(filter.provider)));
13250            out.print(' ');
13251            filter.provider.printComponentShortName(out);
13252            out.print(" filter ");
13253            out.println(Integer.toHexString(System.identityHashCode(filter)));
13254        }
13255
13256        @Override
13257        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13258            return filter.provider;
13259        }
13260
13261        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13262            PackageParser.Provider provider = (PackageParser.Provider)label;
13263            out.print(prefix); out.print(
13264                    Integer.toHexString(System.identityHashCode(provider)));
13265                    out.print(' ');
13266                    provider.printComponentShortName(out);
13267            if (count > 1) {
13268                out.print(" ("); out.print(count); out.print(" filters)");
13269            }
13270            out.println();
13271        }
13272
13273        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13274                = new ArrayMap<ComponentName, PackageParser.Provider>();
13275        private int mFlags;
13276    }
13277
13278    static final class InstantAppIntentResolver
13279            extends IntentResolver<AuxiliaryResolveInfo.AuxiliaryFilter,
13280            AuxiliaryResolveInfo.AuxiliaryFilter> {
13281        /**
13282         * The result that has the highest defined order. Ordering applies on a
13283         * per-package basis. Mapping is from package name to Pair of order and
13284         * EphemeralResolveInfo.
13285         * <p>
13286         * NOTE: This is implemented as a field variable for convenience and efficiency.
13287         * By having a field variable, we're able to track filter ordering as soon as
13288         * a non-zero order is defined. Otherwise, multiple loops across the result set
13289         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13290         * this needs to be contained entirely within {@link #filterResults}.
13291         */
13292        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13293
13294        @Override
13295        protected AuxiliaryResolveInfo.AuxiliaryFilter[] newArray(int size) {
13296            return new AuxiliaryResolveInfo.AuxiliaryFilter[size];
13297        }
13298
13299        @Override
13300        protected boolean isPackageForFilter(String packageName,
13301                AuxiliaryResolveInfo.AuxiliaryFilter responseObj) {
13302            return true;
13303        }
13304
13305        @Override
13306        protected AuxiliaryResolveInfo.AuxiliaryFilter newResult(
13307                AuxiliaryResolveInfo.AuxiliaryFilter responseObj, int match, int userId) {
13308            if (!sUserManager.exists(userId)) {
13309                return null;
13310            }
13311            final String packageName = responseObj.resolveInfo.getPackageName();
13312            final Integer order = responseObj.getOrder();
13313            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13314                    mOrderResult.get(packageName);
13315            // ordering is enabled and this item's order isn't high enough
13316            if (lastOrderResult != null && lastOrderResult.first >= order) {
13317                return null;
13318            }
13319            final InstantAppResolveInfo res = responseObj.resolveInfo;
13320            if (order > 0) {
13321                // non-zero order, enable ordering
13322                mOrderResult.put(packageName, new Pair<>(order, res));
13323            }
13324            return responseObj;
13325        }
13326
13327        @Override
13328        protected void filterResults(List<AuxiliaryResolveInfo.AuxiliaryFilter> results) {
13329            // only do work if ordering is enabled [most of the time it won't be]
13330            if (mOrderResult.size() == 0) {
13331                return;
13332            }
13333            int resultSize = results.size();
13334            for (int i = 0; i < resultSize; i++) {
13335                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13336                final String packageName = info.getPackageName();
13337                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13338                if (savedInfo == null) {
13339                    // package doesn't having ordering
13340                    continue;
13341                }
13342                if (savedInfo.second == info) {
13343                    // circled back to the highest ordered item; remove from order list
13344                    mOrderResult.remove(packageName);
13345                    if (mOrderResult.size() == 0) {
13346                        // no more ordered items
13347                        break;
13348                    }
13349                    continue;
13350                }
13351                // item has a worse order, remove it from the result list
13352                results.remove(i);
13353                resultSize--;
13354                i--;
13355            }
13356        }
13357    }
13358
13359    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13360            new Comparator<ResolveInfo>() {
13361        public int compare(ResolveInfo r1, ResolveInfo r2) {
13362            int v1 = r1.priority;
13363            int v2 = r2.priority;
13364            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13365            if (v1 != v2) {
13366                return (v1 > v2) ? -1 : 1;
13367            }
13368            v1 = r1.preferredOrder;
13369            v2 = r2.preferredOrder;
13370            if (v1 != v2) {
13371                return (v1 > v2) ? -1 : 1;
13372            }
13373            if (r1.isDefault != r2.isDefault) {
13374                return r1.isDefault ? -1 : 1;
13375            }
13376            v1 = r1.match;
13377            v2 = r2.match;
13378            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13379            if (v1 != v2) {
13380                return (v1 > v2) ? -1 : 1;
13381            }
13382            if (r1.system != r2.system) {
13383                return r1.system ? -1 : 1;
13384            }
13385            if (r1.activityInfo != null) {
13386                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13387            }
13388            if (r1.serviceInfo != null) {
13389                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13390            }
13391            if (r1.providerInfo != null) {
13392                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13393            }
13394            return 0;
13395        }
13396    };
13397
13398    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13399            new Comparator<ProviderInfo>() {
13400        public int compare(ProviderInfo p1, ProviderInfo p2) {
13401            final int v1 = p1.initOrder;
13402            final int v2 = p2.initOrder;
13403            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13404        }
13405    };
13406
13407    @Override
13408    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13409            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13410            final int[] userIds, int[] instantUserIds) {
13411        mHandler.post(new Runnable() {
13412            @Override
13413            public void run() {
13414                try {
13415                    final IActivityManager am = ActivityManager.getService();
13416                    if (am == null) return;
13417                    final int[] resolvedUserIds;
13418                    if (userIds == null) {
13419                        resolvedUserIds = am.getRunningUserIds();
13420                    } else {
13421                        resolvedUserIds = userIds;
13422                    }
13423                    doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13424                            resolvedUserIds, false);
13425                    if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) {
13426                        doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13427                                instantUserIds, true);
13428                    }
13429                } catch (RemoteException ex) {
13430                }
13431            }
13432        });
13433    }
13434
13435    @Override
13436    public void notifyPackageAdded(String packageName) {
13437        final PackageListObserver[] observers;
13438        synchronized (mPackages) {
13439            if (mPackageListObservers.size() == 0) {
13440                return;
13441            }
13442            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13443        }
13444        for (int i = observers.length - 1; i >= 0; --i) {
13445            observers[i].onPackageAdded(packageName);
13446        }
13447    }
13448
13449    @Override
13450    public void notifyPackageRemoved(String packageName) {
13451        final PackageListObserver[] observers;
13452        synchronized (mPackages) {
13453            if (mPackageListObservers.size() == 0) {
13454                return;
13455            }
13456            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13457        }
13458        for (int i = observers.length - 1; i >= 0; --i) {
13459            observers[i].onPackageRemoved(packageName);
13460        }
13461    }
13462
13463    /**
13464     * Sends a broadcast for the given action.
13465     * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with
13466     * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows
13467     * the system and applications allowed to see instant applications to receive package
13468     * lifecycle events for instant applications.
13469     */
13470    private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras,
13471            int flags, String targetPkg, IIntentReceiver finishedReceiver,
13472            int[] userIds, boolean isInstantApp)
13473                    throws RemoteException {
13474        for (int id : userIds) {
13475            final Intent intent = new Intent(action,
13476                    pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13477            final String[] requiredPermissions =
13478                    isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null;
13479            if (extras != null) {
13480                intent.putExtras(extras);
13481            }
13482            if (targetPkg != null) {
13483                intent.setPackage(targetPkg);
13484            }
13485            // Modify the UID when posting to other users
13486            int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13487            if (uid > 0 && UserHandle.getUserId(uid) != id) {
13488                uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13489                intent.putExtra(Intent.EXTRA_UID, uid);
13490            }
13491            intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13492            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13493            if (DEBUG_BROADCASTS) {
13494                RuntimeException here = new RuntimeException("here");
13495                here.fillInStackTrace();
13496                Slog.d(TAG, "Sending to user " + id + ": "
13497                        + intent.toShortString(false, true, false, false)
13498                        + " " + intent.getExtras(), here);
13499            }
13500            am.broadcastIntent(null, intent, null, finishedReceiver,
13501                    0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE,
13502                    null, finishedReceiver != null, false, id);
13503        }
13504    }
13505
13506    /**
13507     * Check if the external storage media is available. This is true if there
13508     * is a mounted external storage medium or if the external storage is
13509     * emulated.
13510     */
13511    private boolean isExternalMediaAvailable() {
13512        return mMediaMounted || Environment.isExternalStorageEmulated();
13513    }
13514
13515    @Override
13516    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13517        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13518            return null;
13519        }
13520        if (!isExternalMediaAvailable()) {
13521                // If the external storage is no longer mounted at this point,
13522                // the caller may not have been able to delete all of this
13523                // packages files and can not delete any more.  Bail.
13524            return null;
13525        }
13526        synchronized (mPackages) {
13527            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13528            if (lastPackage != null) {
13529                pkgs.remove(lastPackage);
13530            }
13531            if (pkgs.size() > 0) {
13532                return pkgs.get(0);
13533            }
13534        }
13535        return null;
13536    }
13537
13538    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13539        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13540                userId, andCode ? 1 : 0, packageName);
13541        if (mSystemReady) {
13542            msg.sendToTarget();
13543        } else {
13544            if (mPostSystemReadyMessages == null) {
13545                mPostSystemReadyMessages = new ArrayList<>();
13546            }
13547            mPostSystemReadyMessages.add(msg);
13548        }
13549    }
13550
13551    void startCleaningPackages() {
13552        // reader
13553        if (!isExternalMediaAvailable()) {
13554            return;
13555        }
13556        synchronized (mPackages) {
13557            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13558                return;
13559            }
13560        }
13561        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13562        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13563        IActivityManager am = ActivityManager.getService();
13564        if (am != null) {
13565            int dcsUid = -1;
13566            synchronized (mPackages) {
13567                if (!mDefaultContainerWhitelisted) {
13568                    mDefaultContainerWhitelisted = true;
13569                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13570                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13571                }
13572            }
13573            try {
13574                if (dcsUid > 0) {
13575                    am.backgroundWhitelistUid(dcsUid);
13576                }
13577                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13578                        UserHandle.USER_SYSTEM);
13579            } catch (RemoteException e) {
13580            }
13581        }
13582    }
13583
13584    /**
13585     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13586     * it is acting on behalf on an enterprise or the user).
13587     *
13588     * Note that the ordering of the conditionals in this method is important. The checks we perform
13589     * are as follows, in this order:
13590     *
13591     * 1) If the install is being performed by a system app, we can trust the app to have set the
13592     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13593     *    what it is.
13594     * 2) If the install is being performed by a device or profile owner app, the install reason
13595     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13596     *    set the install reason correctly. If the app targets an older SDK version where install
13597     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13598     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13599     * 3) In all other cases, the install is being performed by a regular app that is neither part
13600     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13601     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13602     *    set to enterprise policy and if so, change it to unknown instead.
13603     */
13604    private int fixUpInstallReason(String installerPackageName, int installerUid,
13605            int installReason) {
13606        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13607                == PERMISSION_GRANTED) {
13608            // If the install is being performed by a system app, we trust that app to have set the
13609            // install reason correctly.
13610            return installReason;
13611        }
13612
13613        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13614            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13615        if (dpm != null) {
13616            ComponentName owner = null;
13617            try {
13618                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13619                if (owner == null) {
13620                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13621                }
13622            } catch (RemoteException e) {
13623            }
13624            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13625                // If the install is being performed by a device or profile owner, the install
13626                // reason should be enterprise policy.
13627                return PackageManager.INSTALL_REASON_POLICY;
13628            }
13629        }
13630
13631        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13632            // If the install is being performed by a regular app (i.e. neither system app nor
13633            // device or profile owner), we have no reason to believe that the app is acting on
13634            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13635            // change it to unknown instead.
13636            return PackageManager.INSTALL_REASON_UNKNOWN;
13637        }
13638
13639        // If the install is being performed by a regular app and the install reason was set to any
13640        // value but enterprise policy, leave the install reason unchanged.
13641        return installReason;
13642    }
13643
13644    /**
13645     * Attempts to bind to the default container service explicitly instead of doing so lazily on
13646     * install commit.
13647     */
13648    void earlyBindToDefContainer() {
13649        mHandler.sendMessage(mHandler.obtainMessage(DEF_CONTAINER_BIND));
13650    }
13651
13652    void installStage(String packageName, File stagedDir,
13653            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13654            String installerPackageName, int installerUid, UserHandle user,
13655            PackageParser.SigningDetails signingDetails) {
13656        if (DEBUG_INSTANT) {
13657            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13658                Slog.d(TAG, "Ephemeral install of " + packageName);
13659            }
13660        }
13661        final VerificationInfo verificationInfo = new VerificationInfo(
13662                sessionParams.originatingUri, sessionParams.referrerUri,
13663                sessionParams.originatingUid, installerUid);
13664
13665        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
13666
13667        final Message msg = mHandler.obtainMessage(INIT_COPY);
13668        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13669                sessionParams.installReason);
13670        final InstallParams params = new InstallParams(origin, null, observer,
13671                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13672                verificationInfo, user, sessionParams.abiOverride,
13673                sessionParams.grantedRuntimePermissions, signingDetails, installReason);
13674        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13675        msg.obj = params;
13676
13677        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13678                System.identityHashCode(msg.obj));
13679        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13680                System.identityHashCode(msg.obj));
13681
13682        mHandler.sendMessage(msg);
13683    }
13684
13685    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13686            int userId) {
13687        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13688        final boolean isInstantApp = pkgSetting.getInstantApp(userId);
13689        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
13690        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
13691        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
13692                false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds);
13693
13694        // Send a session commit broadcast
13695        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
13696        info.installReason = pkgSetting.getInstallReason(userId);
13697        info.appPackageName = packageName;
13698        sendSessionCommitBroadcast(info, userId);
13699    }
13700
13701    @Override
13702    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
13703            boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) {
13704        if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) {
13705            return;
13706        }
13707        Bundle extras = new Bundle(1);
13708        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13709        final int uid = UserHandle.getUid(
13710                (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId);
13711        extras.putInt(Intent.EXTRA_UID, uid);
13712
13713        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13714                packageName, extras, 0, null, null, userIds, instantUserIds);
13715        if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) {
13716            mHandler.post(() -> {
13717                        for (int userId : userIds) {
13718                            sendBootCompletedBroadcastToSystemApp(
13719                                    packageName, includeStopped, userId);
13720                        }
13721                    }
13722            );
13723        }
13724    }
13725
13726    /**
13727     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13728     * automatically without needing an explicit launch.
13729     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13730     */
13731    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
13732            int userId) {
13733        // If user is not running, the app didn't miss any broadcast
13734        if (!mUserManagerInternal.isUserRunning(userId)) {
13735            return;
13736        }
13737        final IActivityManager am = ActivityManager.getService();
13738        try {
13739            // Deliver LOCKED_BOOT_COMPLETED first
13740            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13741                    .setPackage(packageName);
13742            if (includeStopped) {
13743                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13744            }
13745            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13746            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13747                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13748
13749            // Deliver BOOT_COMPLETED only if user is unlocked
13750            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13751                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13752                if (includeStopped) {
13753                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13754                }
13755                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13756                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13757            }
13758        } catch (RemoteException e) {
13759            throw e.rethrowFromSystemServer();
13760        }
13761    }
13762
13763    @Override
13764    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13765            int userId) {
13766        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13767        PackageSetting pkgSetting;
13768        final int callingUid = Binder.getCallingUid();
13769        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13770                true /* requireFullPermission */, true /* checkShell */,
13771                "setApplicationHiddenSetting for user " + userId);
13772
13773        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13774            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13775            return false;
13776        }
13777
13778        long callingId = Binder.clearCallingIdentity();
13779        try {
13780            boolean sendAdded = false;
13781            boolean sendRemoved = false;
13782            // writer
13783            synchronized (mPackages) {
13784                pkgSetting = mSettings.mPackages.get(packageName);
13785                if (pkgSetting == null) {
13786                    return false;
13787                }
13788                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13789                    return false;
13790                }
13791                // Do not allow "android" is being disabled
13792                if ("android".equals(packageName)) {
13793                    Slog.w(TAG, "Cannot hide package: android");
13794                    return false;
13795                }
13796                // Cannot hide static shared libs as they are considered
13797                // a part of the using app (emulating static linking). Also
13798                // static libs are installed always on internal storage.
13799                PackageParser.Package pkg = mPackages.get(packageName);
13800                if (pkg != null && pkg.staticSharedLibName != null) {
13801                    Slog.w(TAG, "Cannot hide package: " + packageName
13802                            + " providing static shared library: "
13803                            + pkg.staticSharedLibName);
13804                    return false;
13805                }
13806                // Only allow protected packages to hide themselves.
13807                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
13808                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13809                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13810                    return false;
13811                }
13812
13813                if (pkgSetting.getHidden(userId) != hidden) {
13814                    pkgSetting.setHidden(hidden, userId);
13815                    mSettings.writePackageRestrictionsLPr(userId);
13816                    if (hidden) {
13817                        sendRemoved = true;
13818                    } else {
13819                        sendAdded = true;
13820                    }
13821                }
13822            }
13823            if (sendAdded) {
13824                sendPackageAddedForUser(packageName, pkgSetting, userId);
13825                return true;
13826            }
13827            if (sendRemoved) {
13828                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13829                        "hiding pkg");
13830                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13831                return true;
13832            }
13833        } finally {
13834            Binder.restoreCallingIdentity(callingId);
13835        }
13836        return false;
13837    }
13838
13839    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13840            int userId) {
13841        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13842        info.removedPackage = packageName;
13843        info.installerPackageName = pkgSetting.installerPackageName;
13844        info.removedUsers = new int[] {userId};
13845        info.broadcastUsers = new int[] {userId};
13846        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13847        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13848    }
13849
13850    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended,
13851            PersistableBundle launcherExtras) {
13852        if (pkgList.length > 0) {
13853            Bundle extras = new Bundle(1);
13854            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13855            if (launcherExtras != null) {
13856                extras.putBundle(Intent.EXTRA_LAUNCHER_EXTRAS,
13857                        new Bundle(launcherExtras.deepCopy()));
13858            }
13859            sendPackageBroadcast(
13860                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13861                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13862                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13863                    new int[] {userId}, null);
13864        }
13865    }
13866
13867    /**
13868     * Returns true if application is not found or there was an error. Otherwise it returns
13869     * the hidden state of the package for the given user.
13870     */
13871    @Override
13872    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13873        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13874        final int callingUid = Binder.getCallingUid();
13875        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13876                true /* requireFullPermission */, false /* checkShell */,
13877                "getApplicationHidden for user " + userId);
13878        PackageSetting ps;
13879        long callingId = Binder.clearCallingIdentity();
13880        try {
13881            // writer
13882            synchronized (mPackages) {
13883                ps = mSettings.mPackages.get(packageName);
13884                if (ps == null) {
13885                    return true;
13886                }
13887                if (filterAppAccessLPr(ps, callingUid, userId)) {
13888                    return true;
13889                }
13890                return ps.getHidden(userId);
13891            }
13892        } finally {
13893            Binder.restoreCallingIdentity(callingId);
13894        }
13895    }
13896
13897    /**
13898     * @hide
13899     */
13900    @Override
13901    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13902            int installReason) {
13903        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13904                null);
13905        PackageSetting pkgSetting;
13906        final int callingUid = Binder.getCallingUid();
13907        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13908                true /* requireFullPermission */, true /* checkShell */,
13909                "installExistingPackage for user " + userId);
13910        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13911            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13912        }
13913
13914        long callingId = Binder.clearCallingIdentity();
13915        try {
13916            boolean installed = false;
13917            final boolean instantApp =
13918                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13919            final boolean fullApp =
13920                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13921
13922            // writer
13923            synchronized (mPackages) {
13924                pkgSetting = mSettings.mPackages.get(packageName);
13925                if (pkgSetting == null) {
13926                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13927                }
13928                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
13929                    // only allow the existing package to be used if it's installed as a full
13930                    // application for at least one user
13931                    boolean installAllowed = false;
13932                    for (int checkUserId : sUserManager.getUserIds()) {
13933                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
13934                        if (installAllowed) {
13935                            break;
13936                        }
13937                    }
13938                    if (!installAllowed) {
13939                        return PackageManager.INSTALL_FAILED_INVALID_URI;
13940                    }
13941                }
13942                if (!pkgSetting.getInstalled(userId)) {
13943                    pkgSetting.setInstalled(true, userId);
13944                    pkgSetting.setHidden(false, userId);
13945                    pkgSetting.setInstallReason(installReason, userId);
13946                    mSettings.writePackageRestrictionsLPr(userId);
13947                    mSettings.writeKernelMappingLPr(pkgSetting);
13948                    installed = true;
13949                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13950                    // upgrade app from instant to full; we don't allow app downgrade
13951                    installed = true;
13952                }
13953                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13954            }
13955
13956            if (installed) {
13957                if (pkgSetting.pkg != null) {
13958                    synchronized (mInstallLock) {
13959                        // We don't need to freeze for a brand new install
13960                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13961                    }
13962                }
13963                sendPackageAddedForUser(packageName, pkgSetting, userId);
13964                synchronized (mPackages) {
13965                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
13966                }
13967            }
13968        } finally {
13969            Binder.restoreCallingIdentity(callingId);
13970        }
13971
13972        return PackageManager.INSTALL_SUCCEEDED;
13973    }
13974
13975    static void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13976            boolean instantApp, boolean fullApp) {
13977        // no state specified; do nothing
13978        if (!instantApp && !fullApp) {
13979            return;
13980        }
13981        if (userId != UserHandle.USER_ALL) {
13982            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13983                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13984            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13985                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13986            }
13987        } else {
13988            for (int currentUserId : sUserManager.getUserIds()) {
13989                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13990                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13991                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13992                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13993                }
13994            }
13995        }
13996    }
13997
13998    boolean isUserRestricted(int userId, String restrictionKey) {
13999        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14000        if (restrictions.getBoolean(restrictionKey, false)) {
14001            Log.w(TAG, "User is restricted: " + restrictionKey);
14002            return true;
14003        }
14004        return false;
14005    }
14006
14007    @Override
14008    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14009            PersistableBundle appExtras, PersistableBundle launcherExtras, String callingPackage,
14010            int userId) {
14011        try {
14012            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.SUSPEND_APPS, null);
14013        } catch (SecurityException e) {
14014            mContext.enforceCallingOrSelfPermission(Manifest.permission.MANAGE_USERS,
14015                    "Callers need to have either " + Manifest.permission.SUSPEND_APPS + " or "
14016                            + Manifest.permission.MANAGE_USERS);
14017        }
14018        final int callingUid = Binder.getCallingUid();
14019        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14020                true /* requireFullPermission */, true /* checkShell */,
14021                "setPackagesSuspended for user " + userId);
14022        if (callingUid != Process.ROOT_UID &&
14023                !UserHandle.isSameApp(getPackageUid(callingPackage, 0, userId), callingUid)) {
14024            throw new IllegalArgumentException("callingPackage " + callingPackage + " does not"
14025                    + " belong to calling app id " + UserHandle.getAppId(callingUid));
14026        }
14027
14028        if (ArrayUtils.isEmpty(packageNames)) {
14029            return packageNames;
14030        }
14031
14032        final List<String> changedPackagesList = new ArrayList<>(packageNames.length);
14033        final List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14034        final long callingId = Binder.clearCallingIdentity();
14035        try {
14036            synchronized (mPackages) {
14037                for (int i = 0; i < packageNames.length; i++) {
14038                    final String packageName = packageNames[i];
14039                    if (callingPackage.equals(packageName)) {
14040                        Slog.w(TAG, "Calling package: " + callingPackage + " trying to "
14041                                + (suspended ? "" : "un") + "suspend itself. Ignoring");
14042                        unactionedPackages.add(packageName);
14043                        continue;
14044                    }
14045                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14046                    if (pkgSetting == null
14047                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14048                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14049                                + "\". Skipping suspending/un-suspending.");
14050                        unactionedPackages.add(packageName);
14051                        continue;
14052                    }
14053                    if (pkgSetting.getSuspended(userId) != suspended) {
14054                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14055                            unactionedPackages.add(packageName);
14056                            continue;
14057                        }
14058                        pkgSetting.setSuspended(suspended, callingPackage, appExtras,
14059                                launcherExtras, userId);
14060                        changedPackagesList.add(packageName);
14061                    }
14062                }
14063            }
14064        } finally {
14065            Binder.restoreCallingIdentity(callingId);
14066        }
14067        if (!changedPackagesList.isEmpty()) {
14068            final String[] changedPackages = changedPackagesList.toArray(
14069                    new String[changedPackagesList.size()]);
14070            sendPackagesSuspendedForUser(changedPackages, userId, suspended, launcherExtras);
14071            sendMyPackageSuspendedOrUnsuspended(changedPackages, suspended, appExtras, userId);
14072            synchronized (mPackages) {
14073                scheduleWritePackageRestrictionsLocked(userId);
14074            }
14075        }
14076
14077        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14078    }
14079
14080    @Override
14081    public PersistableBundle getSuspendedPackageAppExtras(String packageName, int userId) {
14082        final int callingUid = Binder.getCallingUid();
14083        if (getPackageUid(packageName, 0, userId) != callingUid) {
14084            mContext.enforceCallingOrSelfPermission(Manifest.permission.SUSPEND_APPS, null);
14085        }
14086        synchronized (mPackages) {
14087            final PackageSetting ps = mSettings.mPackages.get(packageName);
14088            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14089                throw new IllegalArgumentException("Unknown target package: " + packageName);
14090            }
14091            final PackageUserState packageUserState = ps.readUserState(userId);
14092            if (packageUserState.suspended) {
14093                return packageUserState.suspendedAppExtras;
14094            }
14095            return null;
14096        }
14097    }
14098
14099    @Override
14100    public void setSuspendedPackageAppExtras(String packageName, PersistableBundle appExtras,
14101            int userId) {
14102        final int callingUid = Binder.getCallingUid();
14103        mContext.enforceCallingOrSelfPermission(Manifest.permission.SUSPEND_APPS, null);
14104        synchronized (mPackages) {
14105            final PackageSetting ps = mSettings.mPackages.get(packageName);
14106            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14107                throw new IllegalArgumentException("Unknown target package: " + packageName);
14108            }
14109            final PackageUserState packageUserState = ps.readUserState(userId);
14110            if (packageUserState.suspended) {
14111                packageUserState.suspendedAppExtras = appExtras;
14112                sendMyPackageSuspendedOrUnsuspended(new String[] {packageName}, true, appExtras,
14113                        userId);
14114            }
14115        }
14116    }
14117
14118    private void sendMyPackageSuspendedOrUnsuspended(String[] affectedPackages, boolean suspended,
14119            PersistableBundle appExtras, int userId) {
14120        final String action;
14121        final Bundle intentExtras = new Bundle();
14122        if (suspended) {
14123            action = Intent.ACTION_MY_PACKAGE_SUSPENDED;
14124            if (appExtras != null) {
14125                final Bundle bundledAppExtras = new Bundle(appExtras.deepCopy());
14126                intentExtras.putBundle(Intent.EXTRA_SUSPENDED_PACKAGE_EXTRAS, bundledAppExtras);
14127            }
14128        } else {
14129            action = Intent.ACTION_MY_PACKAGE_UNSUSPENDED;
14130        }
14131        mHandler.post(new Runnable() {
14132            @Override
14133            public void run() {
14134                try {
14135                    final IActivityManager am = ActivityManager.getService();
14136                    if (am == null) {
14137                        Slog.wtf(TAG, "IActivityManager null. Cannot send MY_PACKAGE_ "
14138                                + (suspended ? "" : "UN") + "SUSPENDED broadcasts");
14139                        return;
14140                    }
14141                    final int[] targetUserIds = new int[] {userId};
14142                    for (String packageName : affectedPackages) {
14143                        doSendBroadcast(am, action, null, intentExtras,
14144                                Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, packageName, null,
14145                                targetUserIds, false);
14146                    }
14147                } catch (RemoteException ex) {
14148                    // Shouldn't happen as AMS is in the same process.
14149                }
14150            }
14151        });
14152    }
14153
14154    @Override
14155    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14156        final int callingUid = Binder.getCallingUid();
14157        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14158                true /* requireFullPermission */, false /* checkShell */,
14159                "isPackageSuspendedForUser for user " + userId);
14160        if (getPackageUid(packageName, 0, userId) != callingUid) {
14161            mContext.enforceCallingOrSelfPermission(Manifest.permission.SUSPEND_APPS, null);
14162        }
14163        synchronized (mPackages) {
14164            final PackageSetting ps = mSettings.mPackages.get(packageName);
14165            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14166                throw new IllegalArgumentException("Unknown target package: " + packageName);
14167            }
14168            return ps.getSuspended(userId);
14169        }
14170    }
14171
14172    void onSuspendingPackageRemoved(String packageName, int userId) {
14173        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
14174                : new int[] {userId};
14175        synchronized (mPackages) {
14176            for (PackageSetting ps : mSettings.mPackages.values()) {
14177                for (int user : userIds) {
14178                    final PackageUserState pus = ps.readUserState(user);
14179                    if (pus.suspended && packageName.equals(pus.suspendingPackage)) {
14180                        ps.setSuspended(false, null, null, null, user);
14181                    }
14182                }
14183            }
14184        }
14185    }
14186
14187    @GuardedBy("mPackages")
14188    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14189        if (isPackageDeviceAdmin(packageName, userId)) {
14190            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14191                    + "\": has an active device admin");
14192            return false;
14193        }
14194
14195        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14196        if (packageName.equals(activeLauncherPackageName)) {
14197            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14198                    + "\": contains the active launcher");
14199            return false;
14200        }
14201
14202        if (packageName.equals(mRequiredInstallerPackage)) {
14203            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14204                    + "\": required for package installation");
14205            return false;
14206        }
14207
14208        if (packageName.equals(mRequiredUninstallerPackage)) {
14209            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14210                    + "\": required for package uninstallation");
14211            return false;
14212        }
14213
14214        if (packageName.equals(mRequiredVerifierPackage)) {
14215            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14216                    + "\": required for package verification");
14217            return false;
14218        }
14219
14220        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14221            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14222                    + "\": is the default dialer");
14223            return false;
14224        }
14225
14226        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14227            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14228                    + "\": protected package");
14229            return false;
14230        }
14231
14232        // Cannot suspend static shared libs as they are considered
14233        // a part of the using app (emulating static linking). Also
14234        // static libs are installed always on internal storage.
14235        PackageParser.Package pkg = mPackages.get(packageName);
14236        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14237            Slog.w(TAG, "Cannot suspend package: " + packageName
14238                    + " providing static shared library: "
14239                    + pkg.staticSharedLibName);
14240            return false;
14241        }
14242
14243        if (PLATFORM_PACKAGE_NAME.equals(packageName)) {
14244            Slog.w(TAG, "Cannot suspend package: " + packageName);
14245            return false;
14246        }
14247
14248        return true;
14249    }
14250
14251    private String getActiveLauncherPackageName(int userId) {
14252        Intent intent = new Intent(Intent.ACTION_MAIN);
14253        intent.addCategory(Intent.CATEGORY_HOME);
14254        ResolveInfo resolveInfo = resolveIntent(
14255                intent,
14256                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14257                PackageManager.MATCH_DEFAULT_ONLY,
14258                userId);
14259
14260        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14261    }
14262
14263    private String getDefaultDialerPackageName(int userId) {
14264        synchronized (mPackages) {
14265            return mSettings.getDefaultDialerPackageNameLPw(userId);
14266        }
14267    }
14268
14269    @Override
14270    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14271        mContext.enforceCallingOrSelfPermission(
14272                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14273                "Only package verification agents can verify applications");
14274
14275        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14276        final PackageVerificationResponse response = new PackageVerificationResponse(
14277                verificationCode, Binder.getCallingUid());
14278        msg.arg1 = id;
14279        msg.obj = response;
14280        mHandler.sendMessage(msg);
14281    }
14282
14283    @Override
14284    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14285            long millisecondsToDelay) {
14286        mContext.enforceCallingOrSelfPermission(
14287                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14288                "Only package verification agents can extend verification timeouts");
14289
14290        final PackageVerificationState state = mPendingVerification.get(id);
14291        final PackageVerificationResponse response = new PackageVerificationResponse(
14292                verificationCodeAtTimeout, Binder.getCallingUid());
14293
14294        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14295            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14296        }
14297        if (millisecondsToDelay < 0) {
14298            millisecondsToDelay = 0;
14299        }
14300        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14301                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14302            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14303        }
14304
14305        if ((state != null) && !state.timeoutExtended()) {
14306            state.extendTimeout();
14307
14308            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14309            msg.arg1 = id;
14310            msg.obj = response;
14311            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14312        }
14313    }
14314
14315    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14316            int verificationCode, UserHandle user) {
14317        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14318        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14319        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14320        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14321        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14322
14323        mContext.sendBroadcastAsUser(intent, user,
14324                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14325    }
14326
14327    private ComponentName matchComponentForVerifier(String packageName,
14328            List<ResolveInfo> receivers) {
14329        ActivityInfo targetReceiver = null;
14330
14331        final int NR = receivers.size();
14332        for (int i = 0; i < NR; i++) {
14333            final ResolveInfo info = receivers.get(i);
14334            if (info.activityInfo == null) {
14335                continue;
14336            }
14337
14338            if (packageName.equals(info.activityInfo.packageName)) {
14339                targetReceiver = info.activityInfo;
14340                break;
14341            }
14342        }
14343
14344        if (targetReceiver == null) {
14345            return null;
14346        }
14347
14348        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14349    }
14350
14351    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14352            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14353        if (pkgInfo.verifiers.length == 0) {
14354            return null;
14355        }
14356
14357        final int N = pkgInfo.verifiers.length;
14358        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14359        for (int i = 0; i < N; i++) {
14360            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14361
14362            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14363                    receivers);
14364            if (comp == null) {
14365                continue;
14366            }
14367
14368            final int verifierUid = getUidForVerifier(verifierInfo);
14369            if (verifierUid == -1) {
14370                continue;
14371            }
14372
14373            if (DEBUG_VERIFY) {
14374                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14375                        + " with the correct signature");
14376            }
14377            sufficientVerifiers.add(comp);
14378            verificationState.addSufficientVerifier(verifierUid);
14379        }
14380
14381        return sufficientVerifiers;
14382    }
14383
14384    private int getUidForVerifier(VerifierInfo verifierInfo) {
14385        synchronized (mPackages) {
14386            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14387            if (pkg == null) {
14388                return -1;
14389            } else if (pkg.mSigningDetails.signatures.length != 1) {
14390                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14391                        + " has more than one signature; ignoring");
14392                return -1;
14393            }
14394
14395            /*
14396             * If the public key of the package's signature does not match
14397             * our expected public key, then this is a different package and
14398             * we should skip.
14399             */
14400
14401            final byte[] expectedPublicKey;
14402            try {
14403                final Signature verifierSig = pkg.mSigningDetails.signatures[0];
14404                final PublicKey publicKey = verifierSig.getPublicKey();
14405                expectedPublicKey = publicKey.getEncoded();
14406            } catch (CertificateException e) {
14407                return -1;
14408            }
14409
14410            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14411
14412            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14413                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14414                        + " does not have the expected public key; ignoring");
14415                return -1;
14416            }
14417
14418            return pkg.applicationInfo.uid;
14419        }
14420    }
14421
14422    @Override
14423    public void finishPackageInstall(int token, boolean didLaunch) {
14424        enforceSystemOrRoot("Only the system is allowed to finish installs");
14425
14426        if (DEBUG_INSTALL) {
14427            Slog.v(TAG, "BM finishing package install for " + token);
14428        }
14429        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14430
14431        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14432        mHandler.sendMessage(msg);
14433    }
14434
14435    /**
14436     * Get the verification agent timeout.  Used for both the APK verifier and the
14437     * intent filter verifier.
14438     *
14439     * @return verification timeout in milliseconds
14440     */
14441    private long getVerificationTimeout() {
14442        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14443                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14444                DEFAULT_VERIFICATION_TIMEOUT);
14445    }
14446
14447    /**
14448     * Get the default verification agent response code.
14449     *
14450     * @return default verification response code
14451     */
14452    private int getDefaultVerificationResponse(UserHandle user) {
14453        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14454            return PackageManager.VERIFICATION_REJECT;
14455        }
14456        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14457                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14458                DEFAULT_VERIFICATION_RESPONSE);
14459    }
14460
14461    /**
14462     * Check whether or not package verification has been enabled.
14463     *
14464     * @return true if verification should be performed
14465     */
14466    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14467        if (!DEFAULT_VERIFY_ENABLE) {
14468            return false;
14469        }
14470
14471        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14472
14473        // Check if installing from ADB
14474        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14475            // Do not run verification in a test harness environment
14476            if (ActivityManager.isRunningInTestHarness()) {
14477                return false;
14478            }
14479            if (ensureVerifyAppsEnabled) {
14480                return true;
14481            }
14482            // Check if the developer does not want package verification for ADB installs
14483            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14484                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14485                return false;
14486            }
14487        } else {
14488            // only when not installed from ADB, skip verification for instant apps when
14489            // the installer and verifier are the same.
14490            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14491                if (mInstantAppInstallerActivity != null
14492                        && mInstantAppInstallerActivity.packageName.equals(
14493                                mRequiredVerifierPackage)) {
14494                    try {
14495                        mContext.getSystemService(AppOpsManager.class)
14496                                .checkPackage(installerUid, mRequiredVerifierPackage);
14497                        if (DEBUG_VERIFY) {
14498                            Slog.i(TAG, "disable verification for instant app");
14499                        }
14500                        return false;
14501                    } catch (SecurityException ignore) { }
14502                }
14503            }
14504        }
14505
14506        if (ensureVerifyAppsEnabled) {
14507            return true;
14508        }
14509
14510        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14511                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14512    }
14513
14514    @Override
14515    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14516            throws RemoteException {
14517        mContext.enforceCallingOrSelfPermission(
14518                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14519                "Only intentfilter verification agents can verify applications");
14520
14521        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14522        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14523                Binder.getCallingUid(), verificationCode, failedDomains);
14524        msg.arg1 = id;
14525        msg.obj = response;
14526        mHandler.sendMessage(msg);
14527    }
14528
14529    @Override
14530    public int getIntentVerificationStatus(String packageName, int userId) {
14531        final int callingUid = Binder.getCallingUid();
14532        if (UserHandle.getUserId(callingUid) != userId) {
14533            mContext.enforceCallingOrSelfPermission(
14534                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14535                    "getIntentVerificationStatus" + userId);
14536        }
14537        if (getInstantAppPackageName(callingUid) != null) {
14538            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14539        }
14540        synchronized (mPackages) {
14541            final PackageSetting ps = mSettings.mPackages.get(packageName);
14542            if (ps == null
14543                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14544                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14545            }
14546            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14547        }
14548    }
14549
14550    @Override
14551    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14552        mContext.enforceCallingOrSelfPermission(
14553                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14554
14555        boolean result = false;
14556        synchronized (mPackages) {
14557            final PackageSetting ps = mSettings.mPackages.get(packageName);
14558            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14559                return false;
14560            }
14561            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14562        }
14563        if (result) {
14564            scheduleWritePackageRestrictionsLocked(userId);
14565        }
14566        return result;
14567    }
14568
14569    @Override
14570    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14571            String packageName) {
14572        final int callingUid = Binder.getCallingUid();
14573        if (getInstantAppPackageName(callingUid) != null) {
14574            return ParceledListSlice.emptyList();
14575        }
14576        synchronized (mPackages) {
14577            final PackageSetting ps = mSettings.mPackages.get(packageName);
14578            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14579                return ParceledListSlice.emptyList();
14580            }
14581            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14582        }
14583    }
14584
14585    @Override
14586    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14587        if (TextUtils.isEmpty(packageName)) {
14588            return ParceledListSlice.emptyList();
14589        }
14590        final int callingUid = Binder.getCallingUid();
14591        final int callingUserId = UserHandle.getUserId(callingUid);
14592        synchronized (mPackages) {
14593            PackageParser.Package pkg = mPackages.get(packageName);
14594            if (pkg == null || pkg.activities == null) {
14595                return ParceledListSlice.emptyList();
14596            }
14597            if (pkg.mExtras == null) {
14598                return ParceledListSlice.emptyList();
14599            }
14600            final PackageSetting ps = (PackageSetting) pkg.mExtras;
14601            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14602                return ParceledListSlice.emptyList();
14603            }
14604            final int count = pkg.activities.size();
14605            ArrayList<IntentFilter> result = new ArrayList<>();
14606            for (int n=0; n<count; n++) {
14607                PackageParser.Activity activity = pkg.activities.get(n);
14608                if (activity.intents != null && activity.intents.size() > 0) {
14609                    result.addAll(activity.intents);
14610                }
14611            }
14612            return new ParceledListSlice<>(result);
14613        }
14614    }
14615
14616    @Override
14617    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14618        mContext.enforceCallingOrSelfPermission(
14619                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14620        if (UserHandle.getCallingUserId() != userId) {
14621            mContext.enforceCallingOrSelfPermission(
14622                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14623        }
14624
14625        synchronized (mPackages) {
14626            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14627            if (packageName != null) {
14628                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
14629                        packageName, userId);
14630            }
14631            return result;
14632        }
14633    }
14634
14635    @Override
14636    public String getDefaultBrowserPackageName(int userId) {
14637        if (UserHandle.getCallingUserId() != userId) {
14638            mContext.enforceCallingOrSelfPermission(
14639                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14640        }
14641        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14642            return null;
14643        }
14644        synchronized (mPackages) {
14645            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14646        }
14647    }
14648
14649    /**
14650     * Get the "allow unknown sources" setting.
14651     *
14652     * @return the current "allow unknown sources" setting
14653     */
14654    private int getUnknownSourcesSettings() {
14655        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14656                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14657                -1);
14658    }
14659
14660    @Override
14661    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14662        final int callingUid = Binder.getCallingUid();
14663        if (getInstantAppPackageName(callingUid) != null) {
14664            return;
14665        }
14666        // writer
14667        synchronized (mPackages) {
14668            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14669            if (targetPackageSetting == null
14670                    || filterAppAccessLPr(
14671                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
14672                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14673            }
14674
14675            PackageSetting installerPackageSetting;
14676            if (installerPackageName != null) {
14677                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14678                if (installerPackageSetting == null) {
14679                    throw new IllegalArgumentException("Unknown installer package: "
14680                            + installerPackageName);
14681                }
14682            } else {
14683                installerPackageSetting = null;
14684            }
14685
14686            Signature[] callerSignature;
14687            Object obj = mSettings.getUserIdLPr(callingUid);
14688            if (obj != null) {
14689                if (obj instanceof SharedUserSetting) {
14690                    callerSignature =
14691                            ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
14692                } else if (obj instanceof PackageSetting) {
14693                    callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures;
14694                } else {
14695                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
14696                }
14697            } else {
14698                throw new SecurityException("Unknown calling UID: " + callingUid);
14699            }
14700
14701            // Verify: can't set installerPackageName to a package that is
14702            // not signed with the same cert as the caller.
14703            if (installerPackageSetting != null) {
14704                if (compareSignatures(callerSignature,
14705                        installerPackageSetting.signatures.mSigningDetails.signatures)
14706                        != PackageManager.SIGNATURE_MATCH) {
14707                    throw new SecurityException(
14708                            "Caller does not have same cert as new installer package "
14709                            + installerPackageName);
14710                }
14711            }
14712
14713            // Verify: if target already has an installer package, it must
14714            // be signed with the same cert as the caller.
14715            if (targetPackageSetting.installerPackageName != null) {
14716                PackageSetting setting = mSettings.mPackages.get(
14717                        targetPackageSetting.installerPackageName);
14718                // If the currently set package isn't valid, then it's always
14719                // okay to change it.
14720                if (setting != null) {
14721                    if (compareSignatures(callerSignature,
14722                            setting.signatures.mSigningDetails.signatures)
14723                            != PackageManager.SIGNATURE_MATCH) {
14724                        throw new SecurityException(
14725                                "Caller does not have same cert as old installer package "
14726                                + targetPackageSetting.installerPackageName);
14727                    }
14728                }
14729            }
14730
14731            // Okay!
14732            targetPackageSetting.installerPackageName = installerPackageName;
14733            if (installerPackageName != null) {
14734                mSettings.mInstallerPackages.add(installerPackageName);
14735            }
14736            scheduleWriteSettingsLocked();
14737        }
14738    }
14739
14740    @Override
14741    public void setApplicationCategoryHint(String packageName, int categoryHint,
14742            String callerPackageName) {
14743        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14744            throw new SecurityException("Instant applications don't have access to this method");
14745        }
14746        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14747                callerPackageName);
14748        synchronized (mPackages) {
14749            PackageSetting ps = mSettings.mPackages.get(packageName);
14750            if (ps == null) {
14751                throw new IllegalArgumentException("Unknown target package " + packageName);
14752            }
14753            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14754                throw new IllegalArgumentException("Unknown target package " + packageName);
14755            }
14756            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14757                throw new IllegalArgumentException("Calling package " + callerPackageName
14758                        + " is not installer for " + packageName);
14759            }
14760
14761            if (ps.categoryHint != categoryHint) {
14762                ps.categoryHint = categoryHint;
14763                scheduleWriteSettingsLocked();
14764            }
14765        }
14766    }
14767
14768    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14769        // Queue up an async operation since the package installation may take a little while.
14770        mHandler.post(new Runnable() {
14771            public void run() {
14772                mHandler.removeCallbacks(this);
14773                 // Result object to be returned
14774                PackageInstalledInfo res = new PackageInstalledInfo();
14775                res.setReturnCode(currentStatus);
14776                res.uid = -1;
14777                res.pkg = null;
14778                res.removedInfo = null;
14779                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14780                    args.doPreInstall(res.returnCode);
14781                    synchronized (mInstallLock) {
14782                        installPackageTracedLI(args, res);
14783                    }
14784                    args.doPostInstall(res.returnCode, res.uid);
14785                }
14786
14787                // A restore should be performed at this point if (a) the install
14788                // succeeded, (b) the operation is not an update, and (c) the new
14789                // package has not opted out of backup participation.
14790                final boolean update = res.removedInfo != null
14791                        && res.removedInfo.removedPackage != null;
14792                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14793                boolean doRestore = !update
14794                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14795
14796                // Set up the post-install work request bookkeeping.  This will be used
14797                // and cleaned up by the post-install event handling regardless of whether
14798                // there's a restore pass performed.  Token values are >= 1.
14799                int token;
14800                if (mNextInstallToken < 0) mNextInstallToken = 1;
14801                token = mNextInstallToken++;
14802
14803                PostInstallData data = new PostInstallData(args, res);
14804                mRunningInstalls.put(token, data);
14805                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14806
14807                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14808                    // Pass responsibility to the Backup Manager.  It will perform a
14809                    // restore if appropriate, then pass responsibility back to the
14810                    // Package Manager to run the post-install observer callbacks
14811                    // and broadcasts.
14812                    IBackupManager bm = IBackupManager.Stub.asInterface(
14813                            ServiceManager.getService(Context.BACKUP_SERVICE));
14814                    if (bm != null) {
14815                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14816                                + " to BM for possible restore");
14817                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14818                        try {
14819                            // TODO: http://b/22388012
14820                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14821                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14822                            } else {
14823                                doRestore = false;
14824                            }
14825                        } catch (RemoteException e) {
14826                            // can't happen; the backup manager is local
14827                        } catch (Exception e) {
14828                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14829                            doRestore = false;
14830                        }
14831                    } else {
14832                        Slog.e(TAG, "Backup Manager not found!");
14833                        doRestore = false;
14834                    }
14835                }
14836
14837                if (!doRestore) {
14838                    // No restore possible, or the Backup Manager was mysteriously not
14839                    // available -- just fire the post-install work request directly.
14840                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14841
14842                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14843
14844                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14845                    mHandler.sendMessage(msg);
14846                }
14847            }
14848        });
14849    }
14850
14851    /**
14852     * Callback from PackageSettings whenever an app is first transitioned out of the
14853     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14854     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14855     * here whether the app is the target of an ongoing install, and only send the
14856     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14857     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14858     * handling.
14859     */
14860    void notifyFirstLaunch(final String packageName, final String installerPackage,
14861            final int userId) {
14862        // Serialize this with the rest of the install-process message chain.  In the
14863        // restore-at-install case, this Runnable will necessarily run before the
14864        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14865        // are coherent.  In the non-restore case, the app has already completed install
14866        // and been launched through some other means, so it is not in a problematic
14867        // state for observers to see the FIRST_LAUNCH signal.
14868        mHandler.post(new Runnable() {
14869            @Override
14870            public void run() {
14871                for (int i = 0; i < mRunningInstalls.size(); i++) {
14872                    final PostInstallData data = mRunningInstalls.valueAt(i);
14873                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14874                        continue;
14875                    }
14876                    if (packageName.equals(data.res.pkg.applicationInfo.packageName)) {
14877                        // right package; but is it for the right user?
14878                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14879                            if (userId == data.res.newUsers[uIndex]) {
14880                                if (DEBUG_BACKUP) {
14881                                    Slog.i(TAG, "Package " + packageName
14882                                            + " being restored so deferring FIRST_LAUNCH");
14883                                }
14884                                return;
14885                            }
14886                        }
14887                    }
14888                }
14889                // didn't find it, so not being restored
14890                if (DEBUG_BACKUP) {
14891                    Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH");
14892                }
14893                final boolean isInstantApp = isInstantApp(packageName, userId);
14894                final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
14895                final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
14896                sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds);
14897            }
14898        });
14899    }
14900
14901    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg,
14902            int[] userIds, int[] instantUserIds) {
14903        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14904                installerPkg, null, userIds, instantUserIds);
14905    }
14906
14907    private abstract class HandlerParams {
14908        private static final int MAX_RETRIES = 4;
14909
14910        /**
14911         * Number of times startCopy() has been attempted and had a non-fatal
14912         * error.
14913         */
14914        private int mRetries = 0;
14915
14916        /** User handle for the user requesting the information or installation. */
14917        private final UserHandle mUser;
14918        String traceMethod;
14919        int traceCookie;
14920
14921        HandlerParams(UserHandle user) {
14922            mUser = user;
14923        }
14924
14925        UserHandle getUser() {
14926            return mUser;
14927        }
14928
14929        HandlerParams setTraceMethod(String traceMethod) {
14930            this.traceMethod = traceMethod;
14931            return this;
14932        }
14933
14934        HandlerParams setTraceCookie(int traceCookie) {
14935            this.traceCookie = traceCookie;
14936            return this;
14937        }
14938
14939        final boolean startCopy() {
14940            boolean res;
14941            try {
14942                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14943
14944                if (++mRetries > MAX_RETRIES) {
14945                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14946                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14947                    handleServiceError();
14948                    return false;
14949                } else {
14950                    handleStartCopy();
14951                    res = true;
14952                }
14953            } catch (RemoteException e) {
14954                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14955                mHandler.sendEmptyMessage(MCS_RECONNECT);
14956                res = false;
14957            }
14958            handleReturnCode();
14959            return res;
14960        }
14961
14962        final void serviceError() {
14963            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14964            handleServiceError();
14965            handleReturnCode();
14966        }
14967
14968        abstract void handleStartCopy() throws RemoteException;
14969        abstract void handleServiceError();
14970        abstract void handleReturnCode();
14971    }
14972
14973    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14974        for (File path : paths) {
14975            try {
14976                mcs.clearDirectory(path.getAbsolutePath());
14977            } catch (RemoteException e) {
14978            }
14979        }
14980    }
14981
14982    static class OriginInfo {
14983        /**
14984         * Location where install is coming from, before it has been
14985         * copied/renamed into place. This could be a single monolithic APK
14986         * file, or a cluster directory. This location may be untrusted.
14987         */
14988        final File file;
14989
14990        /**
14991         * Flag indicating that {@link #file} or {@link #cid} has already been
14992         * staged, meaning downstream users don't need to defensively copy the
14993         * contents.
14994         */
14995        final boolean staged;
14996
14997        /**
14998         * Flag indicating that {@link #file} or {@link #cid} is an already
14999         * installed app that is being moved.
15000         */
15001        final boolean existing;
15002
15003        final String resolvedPath;
15004        final File resolvedFile;
15005
15006        static OriginInfo fromNothing() {
15007            return new OriginInfo(null, false, false);
15008        }
15009
15010        static OriginInfo fromUntrustedFile(File file) {
15011            return new OriginInfo(file, false, false);
15012        }
15013
15014        static OriginInfo fromExistingFile(File file) {
15015            return new OriginInfo(file, false, true);
15016        }
15017
15018        static OriginInfo fromStagedFile(File file) {
15019            return new OriginInfo(file, true, false);
15020        }
15021
15022        private OriginInfo(File file, boolean staged, boolean existing) {
15023            this.file = file;
15024            this.staged = staged;
15025            this.existing = existing;
15026
15027            if (file != null) {
15028                resolvedPath = file.getAbsolutePath();
15029                resolvedFile = file;
15030            } else {
15031                resolvedPath = null;
15032                resolvedFile = null;
15033            }
15034        }
15035    }
15036
15037    static class MoveInfo {
15038        final int moveId;
15039        final String fromUuid;
15040        final String toUuid;
15041        final String packageName;
15042        final String dataAppName;
15043        final int appId;
15044        final String seinfo;
15045        final int targetSdkVersion;
15046
15047        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15048                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15049            this.moveId = moveId;
15050            this.fromUuid = fromUuid;
15051            this.toUuid = toUuid;
15052            this.packageName = packageName;
15053            this.dataAppName = dataAppName;
15054            this.appId = appId;
15055            this.seinfo = seinfo;
15056            this.targetSdkVersion = targetSdkVersion;
15057        }
15058    }
15059
15060    static class VerificationInfo {
15061        /** A constant used to indicate that a uid value is not present. */
15062        public static final int NO_UID = -1;
15063
15064        /** URI referencing where the package was downloaded from. */
15065        final Uri originatingUri;
15066
15067        /** HTTP referrer URI associated with the originatingURI. */
15068        final Uri referrer;
15069
15070        /** UID of the application that the install request originated from. */
15071        final int originatingUid;
15072
15073        /** UID of application requesting the install */
15074        final int installerUid;
15075
15076        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15077            this.originatingUri = originatingUri;
15078            this.referrer = referrer;
15079            this.originatingUid = originatingUid;
15080            this.installerUid = installerUid;
15081        }
15082    }
15083
15084    class InstallParams extends HandlerParams {
15085        final OriginInfo origin;
15086        final MoveInfo move;
15087        final IPackageInstallObserver2 observer;
15088        int installFlags;
15089        final String installerPackageName;
15090        final String volumeUuid;
15091        private InstallArgs mArgs;
15092        private int mRet;
15093        final String packageAbiOverride;
15094        final String[] grantedRuntimePermissions;
15095        final VerificationInfo verificationInfo;
15096        final PackageParser.SigningDetails signingDetails;
15097        final int installReason;
15098
15099        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15100                int installFlags, String installerPackageName, String volumeUuid,
15101                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15102                String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) {
15103            super(user);
15104            this.origin = origin;
15105            this.move = move;
15106            this.observer = observer;
15107            this.installFlags = installFlags;
15108            this.installerPackageName = installerPackageName;
15109            this.volumeUuid = volumeUuid;
15110            this.verificationInfo = verificationInfo;
15111            this.packageAbiOverride = packageAbiOverride;
15112            this.grantedRuntimePermissions = grantedPermissions;
15113            this.signingDetails = signingDetails;
15114            this.installReason = installReason;
15115        }
15116
15117        @Override
15118        public String toString() {
15119            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15120                    + " file=" + origin.file + "}";
15121        }
15122
15123        private int installLocationPolicy(PackageInfoLite pkgLite) {
15124            String packageName = pkgLite.packageName;
15125            int installLocation = pkgLite.installLocation;
15126            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15127            // reader
15128            synchronized (mPackages) {
15129                // Currently installed package which the new package is attempting to replace or
15130                // null if no such package is installed.
15131                PackageParser.Package installedPkg = mPackages.get(packageName);
15132                // Package which currently owns the data which the new package will own if installed.
15133                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15134                // will be null whereas dataOwnerPkg will contain information about the package
15135                // which was uninstalled while keeping its data.
15136                PackageParser.Package dataOwnerPkg = installedPkg;
15137                if (dataOwnerPkg  == null) {
15138                    PackageSetting ps = mSettings.mPackages.get(packageName);
15139                    if (ps != null) {
15140                        dataOwnerPkg = ps.pkg;
15141                    }
15142                }
15143
15144                if (dataOwnerPkg != null) {
15145                    // If installed, the package will get access to data left on the device by its
15146                    // predecessor. As a security measure, this is permited only if this is not a
15147                    // version downgrade or if the predecessor package is marked as debuggable and
15148                    // a downgrade is explicitly requested.
15149                    //
15150                    // On debuggable platform builds, downgrades are permitted even for
15151                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15152                    // not offer security guarantees and thus it's OK to disable some security
15153                    // mechanisms to make debugging/testing easier on those builds. However, even on
15154                    // debuggable builds downgrades of packages are permitted only if requested via
15155                    // installFlags. This is because we aim to keep the behavior of debuggable
15156                    // platform builds as close as possible to the behavior of non-debuggable
15157                    // platform builds.
15158                    final boolean downgradeRequested =
15159                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15160                    final boolean packageDebuggable =
15161                                (dataOwnerPkg.applicationInfo.flags
15162                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15163                    final boolean downgradePermitted =
15164                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15165                    if (!downgradePermitted) {
15166                        try {
15167                            checkDowngrade(dataOwnerPkg, pkgLite);
15168                        } catch (PackageManagerException e) {
15169                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15170                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15171                        }
15172                    }
15173                }
15174
15175                if (installedPkg != null) {
15176                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15177                        // Check for updated system application.
15178                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15179                            if (onSd) {
15180                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15181                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15182                            }
15183                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15184                        } else {
15185                            if (onSd) {
15186                                // Install flag overrides everything.
15187                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15188                            }
15189                            // If current upgrade specifies particular preference
15190                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15191                                // Application explicitly specified internal.
15192                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15193                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15194                                // App explictly prefers external. Let policy decide
15195                            } else {
15196                                // Prefer previous location
15197                                if (isExternal(installedPkg)) {
15198                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15199                                }
15200                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15201                            }
15202                        }
15203                    } else {
15204                        // Invalid install. Return error code
15205                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15206                    }
15207                }
15208            }
15209            // All the special cases have been taken care of.
15210            // Return result based on recommended install location.
15211            if (onSd) {
15212                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15213            }
15214            return pkgLite.recommendedInstallLocation;
15215        }
15216
15217        /*
15218         * Invoke remote method to get package information and install
15219         * location values. Override install location based on default
15220         * policy if needed and then create install arguments based
15221         * on the install location.
15222         */
15223        public void handleStartCopy() throws RemoteException {
15224            int ret = PackageManager.INSTALL_SUCCEEDED;
15225
15226            // If we're already staged, we've firmly committed to an install location
15227            if (origin.staged) {
15228                if (origin.file != null) {
15229                    installFlags |= PackageManager.INSTALL_INTERNAL;
15230                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15231                } else {
15232                    throw new IllegalStateException("Invalid stage location");
15233                }
15234            }
15235
15236            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15237            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15238            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15239            PackageInfoLite pkgLite = null;
15240
15241            if (onInt && onSd) {
15242                // Check if both bits are set.
15243                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15244                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15245            } else if (onSd && ephemeral) {
15246                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15247                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15248            } else {
15249                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15250                        packageAbiOverride);
15251
15252                if (DEBUG_INSTANT && ephemeral) {
15253                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15254                }
15255
15256                /*
15257                 * If we have too little free space, try to free cache
15258                 * before giving up.
15259                 */
15260                if (!origin.staged && pkgLite.recommendedInstallLocation
15261                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15262                    // TODO: focus freeing disk space on the target device
15263                    final StorageManager storage = StorageManager.from(mContext);
15264                    final long lowThreshold = storage.getStorageLowBytes(
15265                            Environment.getDataDirectory());
15266
15267                    final long sizeBytes = mContainerService.calculateInstalledSize(
15268                            origin.resolvedPath, packageAbiOverride);
15269
15270                    try {
15271                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15272                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15273                                installFlags, packageAbiOverride);
15274                    } catch (InstallerException e) {
15275                        Slog.w(TAG, "Failed to free cache", e);
15276                    }
15277
15278                    /*
15279                     * The cache free must have deleted the file we
15280                     * downloaded to install.
15281                     *
15282                     * TODO: fix the "freeCache" call to not delete
15283                     *       the file we care about.
15284                     */
15285                    if (pkgLite.recommendedInstallLocation
15286                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15287                        pkgLite.recommendedInstallLocation
15288                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15289                    }
15290                }
15291            }
15292
15293            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15294                int loc = pkgLite.recommendedInstallLocation;
15295                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15296                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15297                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15298                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15299                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15300                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15301                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15302                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15303                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15304                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15305                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15306                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15307                } else {
15308                    // Override with defaults if needed.
15309                    loc = installLocationPolicy(pkgLite);
15310                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15311                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15312                    } else if (!onSd && !onInt) {
15313                        // Override install location with flags
15314                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15315                            // Set the flag to install on external media.
15316                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15317                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15318                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15319                            if (DEBUG_INSTANT) {
15320                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15321                            }
15322                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15323                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15324                                    |PackageManager.INSTALL_INTERNAL);
15325                        } else {
15326                            // Make sure the flag for installing on external
15327                            // media is unset
15328                            installFlags |= PackageManager.INSTALL_INTERNAL;
15329                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15330                        }
15331                    }
15332                }
15333            }
15334
15335            final InstallArgs args = createInstallArgs(this);
15336            mArgs = args;
15337
15338            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15339                // TODO: http://b/22976637
15340                // Apps installed for "all" users use the device owner to verify the app
15341                UserHandle verifierUser = getUser();
15342                if (verifierUser == UserHandle.ALL) {
15343                    verifierUser = UserHandle.SYSTEM;
15344                }
15345
15346                /*
15347                 * Determine if we have any installed package verifiers. If we
15348                 * do, then we'll defer to them to verify the packages.
15349                 */
15350                final int requiredUid = mRequiredVerifierPackage == null ? -1
15351                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15352                                verifierUser.getIdentifier());
15353                final int installerUid =
15354                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15355                if (!origin.existing && requiredUid != -1
15356                        && isVerificationEnabled(
15357                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15358                    final Intent verification = new Intent(
15359                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15360                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15361                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15362                            PACKAGE_MIME_TYPE);
15363                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15364
15365                    // Query all live verifiers based on current user state
15366                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15367                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
15368                            false /*allowDynamicSplits*/);
15369
15370                    if (DEBUG_VERIFY) {
15371                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15372                                + verification.toString() + " with " + pkgLite.verifiers.length
15373                                + " optional verifiers");
15374                    }
15375
15376                    final int verificationId = mPendingVerificationToken++;
15377
15378                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15379
15380                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15381                            installerPackageName);
15382
15383                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15384                            installFlags);
15385
15386                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15387                            pkgLite.packageName);
15388
15389                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15390                            pkgLite.versionCode);
15391
15392                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE,
15393                            pkgLite.getLongVersionCode());
15394
15395                    if (verificationInfo != null) {
15396                        if (verificationInfo.originatingUri != null) {
15397                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15398                                    verificationInfo.originatingUri);
15399                        }
15400                        if (verificationInfo.referrer != null) {
15401                            verification.putExtra(Intent.EXTRA_REFERRER,
15402                                    verificationInfo.referrer);
15403                        }
15404                        if (verificationInfo.originatingUid >= 0) {
15405                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15406                                    verificationInfo.originatingUid);
15407                        }
15408                        if (verificationInfo.installerUid >= 0) {
15409                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15410                                    verificationInfo.installerUid);
15411                        }
15412                    }
15413
15414                    final PackageVerificationState verificationState = new PackageVerificationState(
15415                            requiredUid, args);
15416
15417                    mPendingVerification.append(verificationId, verificationState);
15418
15419                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15420                            receivers, verificationState);
15421
15422                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15423                    final long idleDuration = getVerificationTimeout();
15424
15425                    /*
15426                     * If any sufficient verifiers were listed in the package
15427                     * manifest, attempt to ask them.
15428                     */
15429                    if (sufficientVerifiers != null) {
15430                        final int N = sufficientVerifiers.size();
15431                        if (N == 0) {
15432                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15433                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15434                        } else {
15435                            for (int i = 0; i < N; i++) {
15436                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15437                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15438                                        verifierComponent.getPackageName(), idleDuration,
15439                                        verifierUser.getIdentifier(), false, "package verifier");
15440
15441                                final Intent sufficientIntent = new Intent(verification);
15442                                sufficientIntent.setComponent(verifierComponent);
15443                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15444                            }
15445                        }
15446                    }
15447
15448                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15449                            mRequiredVerifierPackage, receivers);
15450                    if (ret == PackageManager.INSTALL_SUCCEEDED
15451                            && mRequiredVerifierPackage != null) {
15452                        Trace.asyncTraceBegin(
15453                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15454                        /*
15455                         * Send the intent to the required verification agent,
15456                         * but only start the verification timeout after the
15457                         * target BroadcastReceivers have run.
15458                         */
15459                        verification.setComponent(requiredVerifierComponent);
15460                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15461                                mRequiredVerifierPackage, idleDuration,
15462                                verifierUser.getIdentifier(), false, "package verifier");
15463                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15464                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15465                                new BroadcastReceiver() {
15466                                    @Override
15467                                    public void onReceive(Context context, Intent intent) {
15468                                        final Message msg = mHandler
15469                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15470                                        msg.arg1 = verificationId;
15471                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15472                                    }
15473                                }, null, 0, null, null);
15474
15475                        /*
15476                         * We don't want the copy to proceed until verification
15477                         * succeeds, so null out this field.
15478                         */
15479                        mArgs = null;
15480                    }
15481                } else {
15482                    /*
15483                     * No package verification is enabled, so immediately start
15484                     * the remote call to initiate copy using temporary file.
15485                     */
15486                    ret = args.copyApk(mContainerService, true);
15487                }
15488            }
15489
15490            mRet = ret;
15491        }
15492
15493        @Override
15494        void handleReturnCode() {
15495            // If mArgs is null, then MCS couldn't be reached. When it
15496            // reconnects, it will try again to install. At that point, this
15497            // will succeed.
15498            if (mArgs != null) {
15499                processPendingInstall(mArgs, mRet);
15500            }
15501        }
15502
15503        @Override
15504        void handleServiceError() {
15505            mArgs = createInstallArgs(this);
15506            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15507        }
15508    }
15509
15510    private InstallArgs createInstallArgs(InstallParams params) {
15511        if (params.move != null) {
15512            return new MoveInstallArgs(params);
15513        } else {
15514            return new FileInstallArgs(params);
15515        }
15516    }
15517
15518    /**
15519     * Create args that describe an existing installed package. Typically used
15520     * when cleaning up old installs, or used as a move source.
15521     */
15522    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15523            String resourcePath, String[] instructionSets) {
15524        return new FileInstallArgs(codePath, resourcePath, instructionSets);
15525    }
15526
15527    static abstract class InstallArgs {
15528        /** @see InstallParams#origin */
15529        final OriginInfo origin;
15530        /** @see InstallParams#move */
15531        final MoveInfo move;
15532
15533        final IPackageInstallObserver2 observer;
15534        // Always refers to PackageManager flags only
15535        final int installFlags;
15536        final String installerPackageName;
15537        final String volumeUuid;
15538        final UserHandle user;
15539        final String abiOverride;
15540        final String[] installGrantPermissions;
15541        /** If non-null, drop an async trace when the install completes */
15542        final String traceMethod;
15543        final int traceCookie;
15544        final PackageParser.SigningDetails signingDetails;
15545        final int installReason;
15546
15547        // The list of instruction sets supported by this app. This is currently
15548        // only used during the rmdex() phase to clean up resources. We can get rid of this
15549        // if we move dex files under the common app path.
15550        /* nullable */ String[] instructionSets;
15551
15552        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15553                int installFlags, String installerPackageName, String volumeUuid,
15554                UserHandle user, String[] instructionSets,
15555                String abiOverride, String[] installGrantPermissions,
15556                String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails,
15557                int installReason) {
15558            this.origin = origin;
15559            this.move = move;
15560            this.installFlags = installFlags;
15561            this.observer = observer;
15562            this.installerPackageName = installerPackageName;
15563            this.volumeUuid = volumeUuid;
15564            this.user = user;
15565            this.instructionSets = instructionSets;
15566            this.abiOverride = abiOverride;
15567            this.installGrantPermissions = installGrantPermissions;
15568            this.traceMethod = traceMethod;
15569            this.traceCookie = traceCookie;
15570            this.signingDetails = signingDetails;
15571            this.installReason = installReason;
15572        }
15573
15574        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15575        abstract int doPreInstall(int status);
15576
15577        /**
15578         * Rename package into final resting place. All paths on the given
15579         * scanned package should be updated to reflect the rename.
15580         */
15581        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15582        abstract int doPostInstall(int status, int uid);
15583
15584        /** @see PackageSettingBase#codePathString */
15585        abstract String getCodePath();
15586        /** @see PackageSettingBase#resourcePathString */
15587        abstract String getResourcePath();
15588
15589        // Need installer lock especially for dex file removal.
15590        abstract void cleanUpResourcesLI();
15591        abstract boolean doPostDeleteLI(boolean delete);
15592
15593        /**
15594         * Called before the source arguments are copied. This is used mostly
15595         * for MoveParams when it needs to read the source file to put it in the
15596         * destination.
15597         */
15598        int doPreCopy() {
15599            return PackageManager.INSTALL_SUCCEEDED;
15600        }
15601
15602        /**
15603         * Called after the source arguments are copied. This is used mostly for
15604         * MoveParams when it needs to read the source file to put it in the
15605         * destination.
15606         */
15607        int doPostCopy(int uid) {
15608            return PackageManager.INSTALL_SUCCEEDED;
15609        }
15610
15611        protected boolean isFwdLocked() {
15612            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15613        }
15614
15615        protected boolean isExternalAsec() {
15616            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15617        }
15618
15619        protected boolean isEphemeral() {
15620            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15621        }
15622
15623        UserHandle getUser() {
15624            return user;
15625        }
15626    }
15627
15628    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15629        if (!allCodePaths.isEmpty()) {
15630            if (instructionSets == null) {
15631                throw new IllegalStateException("instructionSet == null");
15632            }
15633            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15634            for (String codePath : allCodePaths) {
15635                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15636                    try {
15637                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15638                    } catch (InstallerException ignored) {
15639                    }
15640                }
15641            }
15642        }
15643    }
15644
15645    /**
15646     * Logic to handle installation of non-ASEC applications, including copying
15647     * and renaming logic.
15648     */
15649    class FileInstallArgs extends InstallArgs {
15650        private File codeFile;
15651        private File resourceFile;
15652
15653        // Example topology:
15654        // /data/app/com.example/base.apk
15655        // /data/app/com.example/split_foo.apk
15656        // /data/app/com.example/lib/arm/libfoo.so
15657        // /data/app/com.example/lib/arm64/libfoo.so
15658        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15659
15660        /** New install */
15661        FileInstallArgs(InstallParams params) {
15662            super(params.origin, params.move, params.observer, params.installFlags,
15663                    params.installerPackageName, params.volumeUuid,
15664                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15665                    params.grantedRuntimePermissions,
15666                    params.traceMethod, params.traceCookie, params.signingDetails,
15667                    params.installReason);
15668            if (isFwdLocked()) {
15669                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15670            }
15671        }
15672
15673        /** Existing install */
15674        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15675            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15676                    null, null, null, 0, PackageParser.SigningDetails.UNKNOWN,
15677                    PackageManager.INSTALL_REASON_UNKNOWN);
15678            this.codeFile = (codePath != null) ? new File(codePath) : null;
15679            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15680        }
15681
15682        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15683            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15684            try {
15685                return doCopyApk(imcs, temp);
15686            } finally {
15687                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15688            }
15689        }
15690
15691        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15692            if (origin.staged) {
15693                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15694                codeFile = origin.file;
15695                resourceFile = origin.file;
15696                return PackageManager.INSTALL_SUCCEEDED;
15697            }
15698
15699            try {
15700                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15701                final File tempDir =
15702                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15703                codeFile = tempDir;
15704                resourceFile = tempDir;
15705            } catch (IOException e) {
15706                Slog.w(TAG, "Failed to create copy file: " + e);
15707                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15708            }
15709
15710            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15711                @Override
15712                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15713                    if (!FileUtils.isValidExtFilename(name)) {
15714                        throw new IllegalArgumentException("Invalid filename: " + name);
15715                    }
15716                    try {
15717                        final File file = new File(codeFile, name);
15718                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15719                                O_RDWR | O_CREAT, 0644);
15720                        Os.chmod(file.getAbsolutePath(), 0644);
15721                        return new ParcelFileDescriptor(fd);
15722                    } catch (ErrnoException e) {
15723                        throw new RemoteException("Failed to open: " + e.getMessage());
15724                    }
15725                }
15726            };
15727
15728            int ret = PackageManager.INSTALL_SUCCEEDED;
15729            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15730            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15731                Slog.e(TAG, "Failed to copy package");
15732                return ret;
15733            }
15734
15735            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15736            NativeLibraryHelper.Handle handle = null;
15737            try {
15738                handle = NativeLibraryHelper.Handle.create(codeFile);
15739                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15740                        abiOverride);
15741            } catch (IOException e) {
15742                Slog.e(TAG, "Copying native libraries failed", e);
15743                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15744            } finally {
15745                IoUtils.closeQuietly(handle);
15746            }
15747
15748            return ret;
15749        }
15750
15751        int doPreInstall(int status) {
15752            if (status != PackageManager.INSTALL_SUCCEEDED) {
15753                cleanUp();
15754            }
15755            return status;
15756        }
15757
15758        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15759            if (status != PackageManager.INSTALL_SUCCEEDED) {
15760                cleanUp();
15761                return false;
15762            }
15763
15764            final File targetDir = codeFile.getParentFile();
15765            final File beforeCodeFile = codeFile;
15766            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15767
15768            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15769            try {
15770                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15771            } catch (ErrnoException e) {
15772                Slog.w(TAG, "Failed to rename", e);
15773                return false;
15774            }
15775
15776            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15777                Slog.w(TAG, "Failed to restorecon");
15778                return false;
15779            }
15780
15781            // Reflect the rename internally
15782            codeFile = afterCodeFile;
15783            resourceFile = afterCodeFile;
15784
15785            // Reflect the rename in scanned details
15786            try {
15787                pkg.setCodePath(afterCodeFile.getCanonicalPath());
15788            } catch (IOException e) {
15789                Slog.e(TAG, "Failed to get path: " + afterCodeFile, e);
15790                return false;
15791            }
15792            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15793                    afterCodeFile, pkg.baseCodePath));
15794            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15795                    afterCodeFile, pkg.splitCodePaths));
15796
15797            // Reflect the rename in app info
15798            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15799            pkg.setApplicationInfoCodePath(pkg.codePath);
15800            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15801            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15802            pkg.setApplicationInfoResourcePath(pkg.codePath);
15803            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15804            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15805
15806            return true;
15807        }
15808
15809        int doPostInstall(int status, int uid) {
15810            if (status != PackageManager.INSTALL_SUCCEEDED) {
15811                cleanUp();
15812            }
15813            return status;
15814        }
15815
15816        @Override
15817        String getCodePath() {
15818            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15819        }
15820
15821        @Override
15822        String getResourcePath() {
15823            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15824        }
15825
15826        private boolean cleanUp() {
15827            if (codeFile == null || !codeFile.exists()) {
15828                return false;
15829            }
15830
15831            removeCodePathLI(codeFile);
15832
15833            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15834                resourceFile.delete();
15835            }
15836
15837            return true;
15838        }
15839
15840        void cleanUpResourcesLI() {
15841            // Try enumerating all code paths before deleting
15842            List<String> allCodePaths = Collections.EMPTY_LIST;
15843            if (codeFile != null && codeFile.exists()) {
15844                try {
15845                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15846                    allCodePaths = pkg.getAllCodePaths();
15847                } catch (PackageParserException e) {
15848                    // Ignored; we tried our best
15849                }
15850            }
15851
15852            cleanUp();
15853            removeDexFiles(allCodePaths, instructionSets);
15854        }
15855
15856        boolean doPostDeleteLI(boolean delete) {
15857            // XXX err, shouldn't we respect the delete flag?
15858            cleanUpResourcesLI();
15859            return true;
15860        }
15861    }
15862
15863    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15864            PackageManagerException {
15865        if (copyRet < 0) {
15866            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15867                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15868                throw new PackageManagerException(copyRet, message);
15869            }
15870        }
15871    }
15872
15873    /**
15874     * Extract the StorageManagerService "container ID" from the full code path of an
15875     * .apk.
15876     */
15877    static String cidFromCodePath(String fullCodePath) {
15878        int eidx = fullCodePath.lastIndexOf("/");
15879        String subStr1 = fullCodePath.substring(0, eidx);
15880        int sidx = subStr1.lastIndexOf("/");
15881        return subStr1.substring(sidx+1, eidx);
15882    }
15883
15884    /**
15885     * Logic to handle movement of existing installed applications.
15886     */
15887    class MoveInstallArgs extends InstallArgs {
15888        private File codeFile;
15889        private File resourceFile;
15890
15891        /** New install */
15892        MoveInstallArgs(InstallParams params) {
15893            super(params.origin, params.move, params.observer, params.installFlags,
15894                    params.installerPackageName, params.volumeUuid,
15895                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15896                    params.grantedRuntimePermissions,
15897                    params.traceMethod, params.traceCookie, params.signingDetails,
15898                    params.installReason);
15899        }
15900
15901        int copyApk(IMediaContainerService imcs, boolean temp) {
15902            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15903                    + move.fromUuid + " to " + move.toUuid);
15904            synchronized (mInstaller) {
15905                try {
15906                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15907                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15908                } catch (InstallerException e) {
15909                    Slog.w(TAG, "Failed to move app", e);
15910                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15911                }
15912            }
15913
15914            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15915            resourceFile = codeFile;
15916            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15917
15918            return PackageManager.INSTALL_SUCCEEDED;
15919        }
15920
15921        int doPreInstall(int status) {
15922            if (status != PackageManager.INSTALL_SUCCEEDED) {
15923                cleanUp(move.toUuid);
15924            }
15925            return status;
15926        }
15927
15928        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15929            if (status != PackageManager.INSTALL_SUCCEEDED) {
15930                cleanUp(move.toUuid);
15931                return false;
15932            }
15933
15934            // Reflect the move in app info
15935            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15936            pkg.setApplicationInfoCodePath(pkg.codePath);
15937            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15938            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15939            pkg.setApplicationInfoResourcePath(pkg.codePath);
15940            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15941            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15942
15943            return true;
15944        }
15945
15946        int doPostInstall(int status, int uid) {
15947            if (status == PackageManager.INSTALL_SUCCEEDED) {
15948                cleanUp(move.fromUuid);
15949            } else {
15950                cleanUp(move.toUuid);
15951            }
15952            return status;
15953        }
15954
15955        @Override
15956        String getCodePath() {
15957            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15958        }
15959
15960        @Override
15961        String getResourcePath() {
15962            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15963        }
15964
15965        private boolean cleanUp(String volumeUuid) {
15966            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15967                    move.dataAppName);
15968            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15969            final int[] userIds = sUserManager.getUserIds();
15970            synchronized (mInstallLock) {
15971                // Clean up both app data and code
15972                // All package moves are frozen until finished
15973                for (int userId : userIds) {
15974                    try {
15975                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15976                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15977                    } catch (InstallerException e) {
15978                        Slog.w(TAG, String.valueOf(e));
15979                    }
15980                }
15981                removeCodePathLI(codeFile);
15982            }
15983            return true;
15984        }
15985
15986        void cleanUpResourcesLI() {
15987            throw new UnsupportedOperationException();
15988        }
15989
15990        boolean doPostDeleteLI(boolean delete) {
15991            throw new UnsupportedOperationException();
15992        }
15993    }
15994
15995    static String getAsecPackageName(String packageCid) {
15996        int idx = packageCid.lastIndexOf("-");
15997        if (idx == -1) {
15998            return packageCid;
15999        }
16000        return packageCid.substring(0, idx);
16001    }
16002
16003    // Utility method used to create code paths based on package name and available index.
16004    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16005        String idxStr = "";
16006        int idx = 1;
16007        // Fall back to default value of idx=1 if prefix is not
16008        // part of oldCodePath
16009        if (oldCodePath != null) {
16010            String subStr = oldCodePath;
16011            // Drop the suffix right away
16012            if (suffix != null && subStr.endsWith(suffix)) {
16013                subStr = subStr.substring(0, subStr.length() - suffix.length());
16014            }
16015            // If oldCodePath already contains prefix find out the
16016            // ending index to either increment or decrement.
16017            int sidx = subStr.lastIndexOf(prefix);
16018            if (sidx != -1) {
16019                subStr = subStr.substring(sidx + prefix.length());
16020                if (subStr != null) {
16021                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16022                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16023                    }
16024                    try {
16025                        idx = Integer.parseInt(subStr);
16026                        if (idx <= 1) {
16027                            idx++;
16028                        } else {
16029                            idx--;
16030                        }
16031                    } catch(NumberFormatException e) {
16032                    }
16033                }
16034            }
16035        }
16036        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16037        return prefix + idxStr;
16038    }
16039
16040    private File getNextCodePath(File targetDir, String packageName) {
16041        File result;
16042        SecureRandom random = new SecureRandom();
16043        byte[] bytes = new byte[16];
16044        do {
16045            random.nextBytes(bytes);
16046            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16047            result = new File(targetDir, packageName + "-" + suffix);
16048        } while (result.exists());
16049        return result;
16050    }
16051
16052    // Utility method that returns the relative package path with respect
16053    // to the installation directory. Like say for /data/data/com.test-1.apk
16054    // string com.test-1 is returned.
16055    static String deriveCodePathName(String codePath) {
16056        if (codePath == null) {
16057            return null;
16058        }
16059        final File codeFile = new File(codePath);
16060        final String name = codeFile.getName();
16061        if (codeFile.isDirectory()) {
16062            return name;
16063        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16064            final int lastDot = name.lastIndexOf('.');
16065            return name.substring(0, lastDot);
16066        } else {
16067            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16068            return null;
16069        }
16070    }
16071
16072    static class PackageInstalledInfo {
16073        String name;
16074        int uid;
16075        // The set of users that originally had this package installed.
16076        int[] origUsers;
16077        // The set of users that now have this package installed.
16078        int[] newUsers;
16079        PackageParser.Package pkg;
16080        int returnCode;
16081        String returnMsg;
16082        String installerPackageName;
16083        PackageRemovedInfo removedInfo;
16084        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16085
16086        public void setError(int code, String msg) {
16087            setReturnCode(code);
16088            setReturnMessage(msg);
16089            Slog.w(TAG, msg);
16090        }
16091
16092        public void setError(String msg, PackageParserException e) {
16093            setReturnCode(e.error);
16094            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16095            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16096            for (int i = 0; i < childCount; i++) {
16097                addedChildPackages.valueAt(i).setError(msg, e);
16098            }
16099            Slog.w(TAG, msg, e);
16100        }
16101
16102        public void setError(String msg, PackageManagerException e) {
16103            returnCode = e.error;
16104            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16105            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16106            for (int i = 0; i < childCount; i++) {
16107                addedChildPackages.valueAt(i).setError(msg, e);
16108            }
16109            Slog.w(TAG, msg, e);
16110        }
16111
16112        public void setReturnCode(int returnCode) {
16113            this.returnCode = returnCode;
16114            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16115            for (int i = 0; i < childCount; i++) {
16116                addedChildPackages.valueAt(i).returnCode = returnCode;
16117            }
16118        }
16119
16120        private void setReturnMessage(String returnMsg) {
16121            this.returnMsg = returnMsg;
16122            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16123            for (int i = 0; i < childCount; i++) {
16124                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16125            }
16126        }
16127
16128        // In some error cases we want to convey more info back to the observer
16129        String origPackage;
16130        String origPermission;
16131    }
16132
16133    /*
16134     * Install a non-existing package.
16135     */
16136    private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
16137            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
16138            String volumeUuid, PackageInstalledInfo res, int installReason) {
16139        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
16140
16141        // Remember this for later, in case we need to rollback this install
16142        String pkgName = pkg.packageName;
16143
16144        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
16145
16146        synchronized(mPackages) {
16147            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
16148            if (renamedPackage != null) {
16149                // A package with the same name is already installed, though
16150                // it has been renamed to an older name.  The package we
16151                // are trying to install should be installed as an update to
16152                // the existing one, but that has not been requested, so bail.
16153                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16154                        + " without first uninstalling package running as "
16155                        + renamedPackage);
16156                return;
16157            }
16158            if (mPackages.containsKey(pkgName)) {
16159                // Don't allow installation over an existing package with the same name.
16160                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16161                        + " without first uninstalling.");
16162                return;
16163            }
16164        }
16165
16166        try {
16167            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
16168                    System.currentTimeMillis(), user);
16169
16170            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16171
16172            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16173                prepareAppDataAfterInstallLIF(newPackage);
16174
16175            } else {
16176                // Remove package from internal structures, but keep around any
16177                // data that might have already existed
16178                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16179                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16180            }
16181        } catch (PackageManagerException e) {
16182            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16183        }
16184
16185        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16186    }
16187
16188    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16189        try (DigestInputStream digestStream =
16190                new DigestInputStream(new FileInputStream(file), digest)) {
16191            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16192        }
16193    }
16194
16195    private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
16196            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
16197            PackageInstalledInfo res, int installReason) {
16198        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16199
16200        final PackageParser.Package oldPackage;
16201        final PackageSetting ps;
16202        final String pkgName = pkg.packageName;
16203        final int[] allUsers;
16204        final int[] installedUsers;
16205
16206        synchronized(mPackages) {
16207            oldPackage = mPackages.get(pkgName);
16208            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
16209
16210            // don't allow upgrade to target a release SDK from a pre-release SDK
16211            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
16212                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16213            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
16214                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16215            if (oldTargetsPreRelease
16216                    && !newTargetsPreRelease
16217                    && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16218                Slog.w(TAG, "Can't install package targeting released sdk");
16219                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16220                return;
16221            }
16222
16223            ps = mSettings.mPackages.get(pkgName);
16224
16225            // verify signatures are valid
16226            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16227            if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) {
16228                if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) {
16229                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16230                            "New package not signed by keys specified by upgrade-keysets: "
16231                                    + pkgName);
16232                    return;
16233                }
16234            } else {
16235
16236                // default to original signature matching
16237                if (!pkg.mSigningDetails.checkCapability(oldPackage.mSigningDetails,
16238                        PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)
16239                                && !oldPackage.mSigningDetails.checkCapability(
16240                                        pkg.mSigningDetails,
16241                                        PackageParser.SigningDetails.CertCapabilities.ROLLBACK)) {
16242                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16243                            "New package has a different signature: " + pkgName);
16244                    return;
16245                }
16246            }
16247
16248            // don't allow a system upgrade unless the upgrade hash matches
16249            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) {
16250                byte[] digestBytes = null;
16251                try {
16252                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16253                    updateDigest(digest, new File(pkg.baseCodePath));
16254                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16255                        for (String path : pkg.splitCodePaths) {
16256                            updateDigest(digest, new File(path));
16257                        }
16258                    }
16259                    digestBytes = digest.digest();
16260                } catch (NoSuchAlgorithmException | IOException e) {
16261                    res.setError(INSTALL_FAILED_INVALID_APK,
16262                            "Could not compute hash: " + pkgName);
16263                    return;
16264                }
16265                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16266                    res.setError(INSTALL_FAILED_INVALID_APK,
16267                            "New package fails restrict-update check: " + pkgName);
16268                    return;
16269                }
16270                // retain upgrade restriction
16271                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16272            }
16273
16274            // Check for shared user id changes
16275            String invalidPackageName =
16276                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16277            if (invalidPackageName != null) {
16278                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16279                        "Package " + invalidPackageName + " tried to change user "
16280                                + oldPackage.mSharedUserId);
16281                return;
16282            }
16283
16284            // check if the new package supports all of the abis which the old package supports
16285            boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null;
16286            boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null;
16287            if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) {
16288                res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16289                        "Update to package " + pkgName + " doesn't support multi arch");
16290                return;
16291            }
16292
16293            // In case of rollback, remember per-user/profile install state
16294            allUsers = sUserManager.getUserIds();
16295            installedUsers = ps.queryInstalledUsers(allUsers, true);
16296
16297            // don't allow an upgrade from full to ephemeral
16298            if (isInstantApp) {
16299                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16300                    for (int currentUser : allUsers) {
16301                        if (!ps.getInstantApp(currentUser)) {
16302                            // can't downgrade from full to instant
16303                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16304                                    + " for user: " + currentUser);
16305                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16306                            return;
16307                        }
16308                    }
16309                } else if (!ps.getInstantApp(user.getIdentifier())) {
16310                    // can't downgrade from full to instant
16311                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16312                            + " for user: " + user.getIdentifier());
16313                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16314                    return;
16315                }
16316            }
16317        }
16318
16319        // Update what is removed
16320        res.removedInfo = new PackageRemovedInfo(this);
16321        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16322        res.removedInfo.removedPackage = oldPackage.packageName;
16323        res.removedInfo.installerPackageName = ps.installerPackageName;
16324        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16325        res.removedInfo.isUpdate = true;
16326        res.removedInfo.origUsers = installedUsers;
16327        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16328        for (int i = 0; i < installedUsers.length; i++) {
16329            final int userId = installedUsers[i];
16330            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16331        }
16332
16333        final int childCount = (oldPackage.childPackages != null)
16334                ? oldPackage.childPackages.size() : 0;
16335        for (int i = 0; i < childCount; i++) {
16336            boolean childPackageUpdated = false;
16337            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16338            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16339            if (res.addedChildPackages != null) {
16340                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16341                if (childRes != null) {
16342                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16343                    childRes.removedInfo.removedPackage = childPkg.packageName;
16344                    if (childPs != null) {
16345                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16346                    }
16347                    childRes.removedInfo.isUpdate = true;
16348                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16349                    childPackageUpdated = true;
16350                }
16351            }
16352            if (!childPackageUpdated) {
16353                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16354                childRemovedRes.removedPackage = childPkg.packageName;
16355                if (childPs != null) {
16356                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16357                }
16358                childRemovedRes.isUpdate = false;
16359                childRemovedRes.dataRemoved = true;
16360                synchronized (mPackages) {
16361                    if (childPs != null) {
16362                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16363                    }
16364                }
16365                if (res.removedInfo.removedChildPackages == null) {
16366                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16367                }
16368                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16369            }
16370        }
16371
16372        boolean sysPkg = (isSystemApp(oldPackage));
16373        if (sysPkg) {
16374            // Set the system/privileged/oem/vendor/product flags as needed
16375            final boolean privileged =
16376                    (oldPackage.applicationInfo.privateFlags
16377                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16378            final boolean oem =
16379                    (oldPackage.applicationInfo.privateFlags
16380                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
16381            final boolean vendor =
16382                    (oldPackage.applicationInfo.privateFlags
16383                            & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
16384            final boolean product =
16385                    (oldPackage.applicationInfo.privateFlags
16386                            & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
16387            final @ParseFlags int systemParseFlags = parseFlags;
16388            final @ScanFlags int systemScanFlags = scanFlags
16389                    | SCAN_AS_SYSTEM
16390                    | (privileged ? SCAN_AS_PRIVILEGED : 0)
16391                    | (oem ? SCAN_AS_OEM : 0)
16392                    | (vendor ? SCAN_AS_VENDOR : 0)
16393                    | (product ? SCAN_AS_PRODUCT : 0);
16394
16395            replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags,
16396                    user, allUsers, installerPackageName, res, installReason);
16397        } else {
16398            replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags,
16399                    user, allUsers, installerPackageName, res, installReason);
16400        }
16401    }
16402
16403    @Override
16404    public List<String> getPreviousCodePaths(String packageName) {
16405        final int callingUid = Binder.getCallingUid();
16406        final List<String> result = new ArrayList<>();
16407        if (getInstantAppPackageName(callingUid) != null) {
16408            return result;
16409        }
16410        final PackageSetting ps = mSettings.mPackages.get(packageName);
16411        if (ps != null
16412                && ps.oldCodePaths != null
16413                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
16414            result.addAll(ps.oldCodePaths);
16415        }
16416        return result;
16417    }
16418
16419    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16420            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16421            final @ScanFlags int scanFlags, UserHandle user, int[] allUsers,
16422            String installerPackageName, PackageInstalledInfo res, int installReason) {
16423        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16424                + deletedPackage);
16425
16426        String pkgName = deletedPackage.packageName;
16427        boolean deletedPkg = true;
16428        boolean addedPkg = false;
16429        boolean updatedSettings = false;
16430        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16431        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16432                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16433
16434        final long origUpdateTime = (pkg.mExtras != null)
16435                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16436
16437        // First delete the existing package while retaining the data directory
16438        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16439                res.removedInfo, true, pkg)) {
16440            // If the existing package wasn't successfully deleted
16441            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16442            deletedPkg = false;
16443        } else {
16444            // Successfully deleted the old package; proceed with replace.
16445
16446            // If deleted package lived in a container, give users a chance to
16447            // relinquish resources before killing.
16448            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16449                if (DEBUG_INSTALL) {
16450                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16451                }
16452                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16453                final ArrayList<String> pkgList = new ArrayList<String>(1);
16454                pkgList.add(deletedPackage.applicationInfo.packageName);
16455                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16456            }
16457
16458            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16459                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16460
16461            try {
16462                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
16463                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16464                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16465                        installReason);
16466
16467                // Update the in-memory copy of the previous code paths.
16468                PackageSetting ps = mSettings.mPackages.get(pkgName);
16469                if (!killApp) {
16470                    if (ps.oldCodePaths == null) {
16471                        ps.oldCodePaths = new ArraySet<>();
16472                    }
16473                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16474                    if (deletedPackage.splitCodePaths != null) {
16475                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16476                    }
16477                } else {
16478                    ps.oldCodePaths = null;
16479                }
16480                if (ps.childPackageNames != null) {
16481                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16482                        final String childPkgName = ps.childPackageNames.get(i);
16483                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16484                        childPs.oldCodePaths = ps.oldCodePaths;
16485                    }
16486                }
16487                prepareAppDataAfterInstallLIF(newPackage);
16488                addedPkg = true;
16489                mDexManager.notifyPackageUpdated(newPackage.packageName,
16490                        newPackage.baseCodePath, newPackage.splitCodePaths);
16491            } catch (PackageManagerException e) {
16492                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16493            }
16494        }
16495
16496        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16497            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16498
16499            // Revert all internal state mutations and added folders for the failed install
16500            if (addedPkg) {
16501                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16502                        res.removedInfo, true, null);
16503            }
16504
16505            // Restore the old package
16506            if (deletedPkg) {
16507                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16508                File restoreFile = new File(deletedPackage.codePath);
16509                // Parse old package
16510                boolean oldExternal = isExternal(deletedPackage);
16511                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16512                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16513                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16514                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16515                try {
16516                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16517                            null);
16518                } catch (PackageManagerException e) {
16519                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16520                            + e.getMessage());
16521                    return;
16522                }
16523
16524                synchronized (mPackages) {
16525                    // Ensure the installer package name up to date
16526                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16527
16528                    // Update permissions for restored package
16529                    mPermissionManager.updatePermissions(
16530                            deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16531                            mPermissionCallback);
16532
16533                    mSettings.writeLPr();
16534                }
16535
16536                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16537            }
16538        } else {
16539            synchronized (mPackages) {
16540                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16541                if (ps != null) {
16542                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16543                    if (res.removedInfo.removedChildPackages != null) {
16544                        final int childCount = res.removedInfo.removedChildPackages.size();
16545                        // Iterate in reverse as we may modify the collection
16546                        for (int i = childCount - 1; i >= 0; i--) {
16547                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16548                            if (res.addedChildPackages.containsKey(childPackageName)) {
16549                                res.removedInfo.removedChildPackages.removeAt(i);
16550                            } else {
16551                                PackageRemovedInfo childInfo = res.removedInfo
16552                                        .removedChildPackages.valueAt(i);
16553                                childInfo.removedForAllUsers = mPackages.get(
16554                                        childInfo.removedPackage) == null;
16555                            }
16556                        }
16557                    }
16558                }
16559            }
16560        }
16561    }
16562
16563    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16564            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16565            final @ScanFlags int scanFlags, UserHandle user,
16566            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16567            int installReason) {
16568        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16569                + ", old=" + deletedPackage);
16570
16571        final boolean disabledSystem;
16572
16573        // Remove existing system package
16574        removePackageLI(deletedPackage, true);
16575
16576        synchronized (mPackages) {
16577            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16578        }
16579        if (!disabledSystem) {
16580            // We didn't need to disable the .apk as a current system package,
16581            // which means we are replacing another update that is already
16582            // installed.  We need to make sure to delete the older one's .apk.
16583            res.removedInfo.args = createInstallArgsForExisting(0,
16584                    deletedPackage.applicationInfo.getCodePath(),
16585                    deletedPackage.applicationInfo.getResourcePath(),
16586                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16587        } else {
16588            res.removedInfo.args = null;
16589        }
16590
16591        // Successfully disabled the old package. Now proceed with re-installation
16592        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16593                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16594
16595        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16596        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16597                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16598
16599        PackageParser.Package newPackage = null;
16600        try {
16601            // Add the package to the internal data structures
16602            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
16603
16604            // Set the update and install times
16605            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16606            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16607                    System.currentTimeMillis());
16608
16609            // Update the package dynamic state if succeeded
16610            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16611                // Now that the install succeeded make sure we remove data
16612                // directories for any child package the update removed.
16613                final int deletedChildCount = (deletedPackage.childPackages != null)
16614                        ? deletedPackage.childPackages.size() : 0;
16615                final int newChildCount = (newPackage.childPackages != null)
16616                        ? newPackage.childPackages.size() : 0;
16617                for (int i = 0; i < deletedChildCount; i++) {
16618                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16619                    boolean childPackageDeleted = true;
16620                    for (int j = 0; j < newChildCount; j++) {
16621                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16622                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16623                            childPackageDeleted = false;
16624                            break;
16625                        }
16626                    }
16627                    if (childPackageDeleted) {
16628                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16629                                deletedChildPkg.packageName);
16630                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16631                            PackageRemovedInfo removedChildRes = res.removedInfo
16632                                    .removedChildPackages.get(deletedChildPkg.packageName);
16633                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16634                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16635                        }
16636                    }
16637                }
16638
16639                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16640                        installReason);
16641                prepareAppDataAfterInstallLIF(newPackage);
16642
16643                mDexManager.notifyPackageUpdated(newPackage.packageName,
16644                            newPackage.baseCodePath, newPackage.splitCodePaths);
16645            }
16646        } catch (PackageManagerException e) {
16647            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16648            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16649        }
16650
16651        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16652            // Re installation failed. Restore old information
16653            // Remove new pkg information
16654            if (newPackage != null) {
16655                removeInstalledPackageLI(newPackage, true);
16656            }
16657            // Add back the old system package
16658            try {
16659                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16660            } catch (PackageManagerException e) {
16661                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16662            }
16663
16664            synchronized (mPackages) {
16665                if (disabledSystem) {
16666                    enableSystemPackageLPw(deletedPackage);
16667                }
16668
16669                // Ensure the installer package name up to date
16670                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16671
16672                // Update permissions for restored package
16673                mPermissionManager.updatePermissions(
16674                        deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16675                        mPermissionCallback);
16676
16677                mSettings.writeLPr();
16678            }
16679
16680            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16681                    + " after failed upgrade");
16682        }
16683    }
16684
16685    /**
16686     * Checks whether the parent or any of the child packages have a change shared
16687     * user. For a package to be a valid update the shred users of the parent and
16688     * the children should match. We may later support changing child shared users.
16689     * @param oldPkg The updated package.
16690     * @param newPkg The update package.
16691     * @return The shared user that change between the versions.
16692     */
16693    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16694            PackageParser.Package newPkg) {
16695        // Check parent shared user
16696        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16697            return newPkg.packageName;
16698        }
16699        // Check child shared users
16700        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16701        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16702        for (int i = 0; i < newChildCount; i++) {
16703            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16704            // If this child was present, did it have the same shared user?
16705            for (int j = 0; j < oldChildCount; j++) {
16706                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16707                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16708                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16709                    return newChildPkg.packageName;
16710                }
16711            }
16712        }
16713        return null;
16714    }
16715
16716    private void removeNativeBinariesLI(PackageSetting ps) {
16717        // Remove the lib path for the parent package
16718        if (ps != null) {
16719            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16720            // Remove the lib path for the child packages
16721            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16722            for (int i = 0; i < childCount; i++) {
16723                PackageSetting childPs = null;
16724                synchronized (mPackages) {
16725                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16726                }
16727                if (childPs != null) {
16728                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16729                            .legacyNativeLibraryPathString);
16730                }
16731            }
16732        }
16733    }
16734
16735    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16736        // Enable the parent package
16737        mSettings.enableSystemPackageLPw(pkg.packageName);
16738        // Enable the child packages
16739        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16740        for (int i = 0; i < childCount; i++) {
16741            PackageParser.Package childPkg = pkg.childPackages.get(i);
16742            mSettings.enableSystemPackageLPw(childPkg.packageName);
16743        }
16744    }
16745
16746    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16747            PackageParser.Package newPkg) {
16748        // Disable the parent package (parent always replaced)
16749        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16750        // Disable the child packages
16751        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16752        for (int i = 0; i < childCount; i++) {
16753            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16754            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16755            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16756        }
16757        return disabled;
16758    }
16759
16760    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16761            String installerPackageName) {
16762        // Enable the parent package
16763        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16764        // Enable the child packages
16765        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16766        for (int i = 0; i < childCount; i++) {
16767            PackageParser.Package childPkg = pkg.childPackages.get(i);
16768            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16769        }
16770    }
16771
16772    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16773            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16774        // Update the parent package setting
16775        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16776                res, user, installReason);
16777        // Update the child packages setting
16778        final int childCount = (newPackage.childPackages != null)
16779                ? newPackage.childPackages.size() : 0;
16780        for (int i = 0; i < childCount; i++) {
16781            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16782            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16783            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16784                    childRes.origUsers, childRes, user, installReason);
16785        }
16786    }
16787
16788    private void updateSettingsInternalLI(PackageParser.Package pkg,
16789            String installerPackageName, int[] allUsers, int[] installedForUsers,
16790            PackageInstalledInfo res, UserHandle user, int installReason) {
16791        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16792
16793        final String pkgName = pkg.packageName;
16794
16795        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath);
16796        synchronized (mPackages) {
16797// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions
16798            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
16799                    mPermissionCallback);
16800            // For system-bundled packages, we assume that installing an upgraded version
16801            // of the package implies that the user actually wants to run that new code,
16802            // so we enable the package.
16803            PackageSetting ps = mSettings.mPackages.get(pkgName);
16804            final int userId = user.getIdentifier();
16805            if (ps != null) {
16806                if (isSystemApp(pkg)) {
16807                    if (DEBUG_INSTALL) {
16808                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16809                    }
16810                    // Enable system package for requested users
16811                    if (res.origUsers != null) {
16812                        for (int origUserId : res.origUsers) {
16813                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16814                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16815                                        origUserId, installerPackageName);
16816                            }
16817                        }
16818                    }
16819                    // Also convey the prior install/uninstall state
16820                    if (allUsers != null && installedForUsers != null) {
16821                        for (int currentUserId : allUsers) {
16822                            final boolean installed = ArrayUtils.contains(
16823                                    installedForUsers, currentUserId);
16824                            if (DEBUG_INSTALL) {
16825                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16826                            }
16827                            ps.setInstalled(installed, currentUserId);
16828                        }
16829                        // these install state changes will be persisted in the
16830                        // upcoming call to mSettings.writeLPr().
16831                    }
16832                }
16833                // It's implied that when a user requests installation, they want the app to be
16834                // installed and enabled.
16835                if (userId != UserHandle.USER_ALL) {
16836                    ps.setInstalled(true, userId);
16837                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16838                }
16839
16840                // When replacing an existing package, preserve the original install reason for all
16841                // users that had the package installed before.
16842                final Set<Integer> previousUserIds = new ArraySet<>();
16843                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16844                    final int installReasonCount = res.removedInfo.installReasons.size();
16845                    for (int i = 0; i < installReasonCount; i++) {
16846                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16847                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16848                        ps.setInstallReason(previousInstallReason, previousUserId);
16849                        previousUserIds.add(previousUserId);
16850                    }
16851                }
16852
16853                // Set install reason for users that are having the package newly installed.
16854                if (userId == UserHandle.USER_ALL) {
16855                    for (int currentUserId : sUserManager.getUserIds()) {
16856                        if (!previousUserIds.contains(currentUserId)) {
16857                            ps.setInstallReason(installReason, currentUserId);
16858                        }
16859                    }
16860                } else if (!previousUserIds.contains(userId)) {
16861                    ps.setInstallReason(installReason, userId);
16862                }
16863                mSettings.writeKernelMappingLPr(ps);
16864            }
16865            res.name = pkgName;
16866            res.uid = pkg.applicationInfo.uid;
16867            res.pkg = pkg;
16868            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16869            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16870            //to update install status
16871            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16872            mSettings.writeLPr();
16873            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16874        }
16875
16876        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16877    }
16878
16879    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16880        try {
16881            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16882            installPackageLI(args, res);
16883        } finally {
16884            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16885        }
16886    }
16887
16888    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16889        final int installFlags = args.installFlags;
16890        final String installerPackageName = args.installerPackageName;
16891        final String volumeUuid = args.volumeUuid;
16892        final File tmpPackageFile = new File(args.getCodePath());
16893        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16894        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16895                || (args.volumeUuid != null));
16896        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16897        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16898        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16899        final boolean virtualPreload =
16900                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
16901        boolean replace = false;
16902        @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16903        if (args.move != null) {
16904            // moving a complete application; perform an initial scan on the new install location
16905            scanFlags |= SCAN_INITIAL;
16906        }
16907        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16908            scanFlags |= SCAN_DONT_KILL_APP;
16909        }
16910        if (instantApp) {
16911            scanFlags |= SCAN_AS_INSTANT_APP;
16912        }
16913        if (fullApp) {
16914            scanFlags |= SCAN_AS_FULL_APP;
16915        }
16916        if (virtualPreload) {
16917            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
16918        }
16919
16920        // Result object to be returned
16921        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16922        res.installerPackageName = installerPackageName;
16923
16924        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16925
16926        // Sanity check
16927        if (instantApp && (forwardLocked || onExternal)) {
16928            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16929                    + " external=" + onExternal);
16930            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16931            return;
16932        }
16933
16934        // Retrieve PackageSettings and parse package
16935        @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16936                | PackageParser.PARSE_ENFORCE_CODE
16937                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16938                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16939                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16940        PackageParser pp = new PackageParser();
16941        pp.setSeparateProcesses(mSeparateProcesses);
16942        pp.setDisplayMetrics(mMetrics);
16943        pp.setCallback(mPackageParserCallback);
16944
16945        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16946        final PackageParser.Package pkg;
16947        try {
16948            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16949            DexMetadataHelper.validatePackageDexMetadata(pkg);
16950        } catch (PackageParserException e) {
16951            res.setError("Failed parse during installPackageLI", e);
16952            return;
16953        } finally {
16954            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16955        }
16956
16957        // Instant apps have several additional install-time checks.
16958        if (instantApp) {
16959            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
16960                Slog.w(TAG,
16961                        "Instant app package " + pkg.packageName + " does not target at least O");
16962                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16963                        "Instant app package must target at least O");
16964                return;
16965            }
16966            if (pkg.applicationInfo.targetSandboxVersion != 2) {
16967                Slog.w(TAG, "Instant app package " + pkg.packageName
16968                        + " does not target targetSandboxVersion 2");
16969                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16970                        "Instant app package must use targetSandboxVersion 2");
16971                return;
16972            }
16973            if (pkg.mSharedUserId != null) {
16974                Slog.w(TAG, "Instant app package " + pkg.packageName
16975                        + " may not declare sharedUserId.");
16976                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16977                        "Instant app package may not declare a sharedUserId");
16978                return;
16979            }
16980        }
16981
16982        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16983            // Static shared libraries have synthetic package names
16984            renameStaticSharedLibraryPackage(pkg);
16985
16986            // No static shared libs on external storage
16987            if (onExternal) {
16988                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16989                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16990                        "Packages declaring static-shared libs cannot be updated");
16991                return;
16992            }
16993        }
16994
16995        // If we are installing a clustered package add results for the children
16996        if (pkg.childPackages != null) {
16997            synchronized (mPackages) {
16998                final int childCount = pkg.childPackages.size();
16999                for (int i = 0; i < childCount; i++) {
17000                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17001                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17002                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17003                    childRes.pkg = childPkg;
17004                    childRes.name = childPkg.packageName;
17005                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17006                    if (childPs != null) {
17007                        childRes.origUsers = childPs.queryInstalledUsers(
17008                                sUserManager.getUserIds(), true);
17009                    }
17010                    if ((mPackages.containsKey(childPkg.packageName))) {
17011                        childRes.removedInfo = new PackageRemovedInfo(this);
17012                        childRes.removedInfo.removedPackage = childPkg.packageName;
17013                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17014                    }
17015                    if (res.addedChildPackages == null) {
17016                        res.addedChildPackages = new ArrayMap<>();
17017                    }
17018                    res.addedChildPackages.put(childPkg.packageName, childRes);
17019                }
17020            }
17021        }
17022
17023        // If package doesn't declare API override, mark that we have an install
17024        // time CPU ABI override.
17025        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17026            pkg.cpuAbiOverride = args.abiOverride;
17027        }
17028
17029        String pkgName = res.name = pkg.packageName;
17030        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17031            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17032                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17033                return;
17034            }
17035        }
17036
17037        try {
17038            // either use what we've been given or parse directly from the APK
17039            if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) {
17040                pkg.setSigningDetails(args.signingDetails);
17041            } else {
17042                PackageParser.collectCertificates(pkg, false /* skipVerify */);
17043            }
17044        } catch (PackageParserException e) {
17045            res.setError("Failed collect during installPackageLI", e);
17046            return;
17047        }
17048
17049        if (instantApp && pkg.mSigningDetails.signatureSchemeVersion
17050                < SignatureSchemeVersion.SIGNING_BLOCK_V2) {
17051            Slog.w(TAG, "Instant app package " + pkg.packageName
17052                    + " is not signed with at least APK Signature Scheme v2");
17053            res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17054                    "Instant app package must be signed with APK Signature Scheme v2 or greater");
17055            return;
17056        }
17057
17058        // Get rid of all references to package scan path via parser.
17059        pp = null;
17060        String oldCodePath = null;
17061        boolean systemApp = false;
17062        synchronized (mPackages) {
17063            // Check if installing already existing package
17064            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
17065                String oldName = mSettings.getRenamedPackageLPr(pkgName);
17066                if (pkg.mOriginalPackages != null
17067                        && pkg.mOriginalPackages.contains(oldName)
17068                        && mPackages.containsKey(oldName)) {
17069                    // This package is derived from an original package,
17070                    // and this device has been updating from that original
17071                    // name.  We must continue using the original name, so
17072                    // rename the new package here.
17073                    pkg.setPackageName(oldName);
17074                    pkgName = pkg.packageName;
17075                    replace = true;
17076                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
17077                            + oldName + " pkgName=" + pkgName);
17078                } else if (mPackages.containsKey(pkgName)) {
17079                    // This package, under its official name, already exists
17080                    // on the device; we should replace it.
17081                    replace = true;
17082                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
17083                }
17084
17085                // Child packages are installed through the parent package
17086                if (pkg.parentPackage != null) {
17087                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17088                            "Package " + pkg.packageName + " is child of package "
17089                                    + pkg.parentPackage.parentPackage + ". Child packages "
17090                                    + "can be updated only through the parent package.");
17091                    return;
17092                }
17093
17094                if (replace) {
17095                    // Prevent apps opting out from runtime permissions
17096                    PackageParser.Package oldPackage = mPackages.get(pkgName);
17097                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
17098                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
17099                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
17100                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
17101                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
17102                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
17103                                        + " doesn't support runtime permissions but the old"
17104                                        + " target SDK " + oldTargetSdk + " does.");
17105                        return;
17106                    }
17107                    // Prevent persistent apps from being updated
17108                    if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) {
17109                        res.setError(PackageManager.INSTALL_FAILED_INVALID_APK,
17110                                "Package " + oldPackage.packageName + " is a persistent app. "
17111                                        + "Persistent apps are not updateable.");
17112                        return;
17113                    }
17114                    // Prevent apps from downgrading their targetSandbox.
17115                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
17116                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
17117                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
17118                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17119                                "Package " + pkg.packageName + " new target sandbox "
17120                                + newTargetSandbox + " is incompatible with the previous value of"
17121                                + oldTargetSandbox + ".");
17122                        return;
17123                    }
17124
17125                    // Prevent installing of child packages
17126                    if (oldPackage.parentPackage != null) {
17127                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17128                                "Package " + pkg.packageName + " is child of package "
17129                                        + oldPackage.parentPackage + ". Child packages "
17130                                        + "can be updated only through the parent package.");
17131                        return;
17132                    }
17133                }
17134            }
17135
17136            PackageSetting ps = mSettings.mPackages.get(pkgName);
17137            if (ps != null) {
17138                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
17139
17140                // Static shared libs have same package with different versions where
17141                // we internally use a synthetic package name to allow multiple versions
17142                // of the same package, therefore we need to compare signatures against
17143                // the package setting for the latest library version.
17144                PackageSetting signatureCheckPs = ps;
17145                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17146                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
17147                    if (libraryEntry != null) {
17148                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17149                    }
17150                }
17151
17152                // Quick sanity check that we're signed correctly if updating;
17153                // we'll check this again later when scanning, but we want to
17154                // bail early here before tripping over redefined permissions.
17155                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17156                if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
17157                    if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
17158                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17159                                + pkg.packageName + " upgrade keys do not match the "
17160                                + "previously installed version");
17161                        return;
17162                    }
17163                } else {
17164                    try {
17165                        final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
17166                        final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
17167                        // We don't care about disabledPkgSetting on install for now.
17168                        final boolean compatMatch = verifySignatures(
17169                                signatureCheckPs, null, pkg.mSigningDetails, compareCompat,
17170                                compareRecover);
17171                        // The new KeySets will be re-added later in the scanning process.
17172                        if (compatMatch) {
17173                            synchronized (mPackages) {
17174                                ksms.removeAppKeySetDataLPw(pkg.packageName);
17175                            }
17176                        }
17177                    } catch (PackageManagerException e) {
17178                        res.setError(e.error, e.getMessage());
17179                        return;
17180                    }
17181                }
17182
17183                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17184                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17185                    systemApp = (ps.pkg.applicationInfo.flags &
17186                            ApplicationInfo.FLAG_SYSTEM) != 0;
17187                }
17188                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17189            }
17190
17191            int N = pkg.permissions.size();
17192            for (int i = N-1; i >= 0; i--) {
17193                final PackageParser.Permission perm = pkg.permissions.get(i);
17194                final BasePermission bp =
17195                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
17196
17197                // Don't allow anyone but the system to define ephemeral permissions.
17198                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
17199                        && !systemApp) {
17200                    Slog.w(TAG, "Non-System package " + pkg.packageName
17201                            + " attempting to delcare ephemeral permission "
17202                            + perm.info.name + "; Removing ephemeral.");
17203                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
17204                }
17205
17206                // Check whether the newly-scanned package wants to define an already-defined perm
17207                if (bp != null) {
17208                    // If the defining package is signed with our cert, it's okay.  This
17209                    // also includes the "updating the same package" case, of course.
17210                    // "updating same package" could also involve key-rotation.
17211                    final boolean sigsOk;
17212                    final String sourcePackageName = bp.getSourcePackageName();
17213                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
17214                    final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17215                    if (sourcePackageName.equals(pkg.packageName)
17216                            && (ksms.shouldCheckUpgradeKeySetLocked(
17217                                    sourcePackageSetting, scanFlags))) {
17218                        sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg);
17219                    } else {
17220
17221                        // in the event of signing certificate rotation, we need to see if the
17222                        // package's certificate has rotated from the current one, or if it is an
17223                        // older certificate with which the current is ok with sharing permissions
17224                        if (sourcePackageSetting.signatures.mSigningDetails.checkCapability(
17225                                        pkg.mSigningDetails,
17226                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17227                            sigsOk = true;
17228                        } else if (pkg.mSigningDetails.checkCapability(
17229                                        sourcePackageSetting.signatures.mSigningDetails,
17230                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17231
17232                            // the scanned package checks out, has signing certificate rotation
17233                            // history, and is newer; bring it over
17234                            sourcePackageSetting.signatures.mSigningDetails = pkg.mSigningDetails;
17235                            sigsOk = true;
17236                        } else {
17237                            sigsOk = false;
17238                        }
17239                    }
17240                    if (!sigsOk) {
17241                        // If the owning package is the system itself, we log but allow
17242                        // install to proceed; we fail the install on all other permission
17243                        // redefinitions.
17244                        if (!sourcePackageName.equals("android")) {
17245                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17246                                    + pkg.packageName + " attempting to redeclare permission "
17247                                    + perm.info.name + " already owned by " + sourcePackageName);
17248                            res.origPermission = perm.info.name;
17249                            res.origPackage = sourcePackageName;
17250                            return;
17251                        } else {
17252                            Slog.w(TAG, "Package " + pkg.packageName
17253                                    + " attempting to redeclare system permission "
17254                                    + perm.info.name + "; ignoring new declaration");
17255                            pkg.permissions.remove(i);
17256                        }
17257                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17258                        // Prevent apps to change protection level to dangerous from any other
17259                        // type as this would allow a privilege escalation where an app adds a
17260                        // normal/signature permission in other app's group and later redefines
17261                        // it as dangerous leading to the group auto-grant.
17262                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17263                                == PermissionInfo.PROTECTION_DANGEROUS) {
17264                            if (bp != null && !bp.isRuntime()) {
17265                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17266                                        + "non-runtime permission " + perm.info.name
17267                                        + " to runtime; keeping old protection level");
17268                                perm.info.protectionLevel = bp.getProtectionLevel();
17269                            }
17270                        }
17271                    }
17272                }
17273            }
17274        }
17275
17276        if (systemApp) {
17277            if (onExternal) {
17278                // Abort update; system app can't be replaced with app on sdcard
17279                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17280                        "Cannot install updates to system apps on sdcard");
17281                return;
17282            } else if (instantApp) {
17283                // Abort update; system app can't be replaced with an instant app
17284                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17285                        "Cannot update a system app with an instant app");
17286                return;
17287            }
17288        }
17289
17290        if (args.move != null) {
17291            // We did an in-place move, so dex is ready to roll
17292            scanFlags |= SCAN_NO_DEX;
17293            scanFlags |= SCAN_MOVE;
17294
17295            synchronized (mPackages) {
17296                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17297                if (ps == null) {
17298                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17299                            "Missing settings for moved package " + pkgName);
17300                }
17301
17302                // We moved the entire application as-is, so bring over the
17303                // previously derived ABI information.
17304                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17305                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17306            }
17307
17308        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17309            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17310            scanFlags |= SCAN_NO_DEX;
17311
17312            try {
17313                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17314                    args.abiOverride : pkg.cpuAbiOverride);
17315                final boolean extractNativeLibs = !pkg.isLibrary();
17316                derivePackageAbi(pkg, abiOverride, extractNativeLibs);
17317            } catch (PackageManagerException pme) {
17318                Slog.e(TAG, "Error deriving application ABI", pme);
17319                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17320                return;
17321            }
17322
17323            // Shared libraries for the package need to be updated.
17324            synchronized (mPackages) {
17325                try {
17326                    updateSharedLibrariesLPr(pkg, null);
17327                } catch (PackageManagerException e) {
17328                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17329                }
17330            }
17331        }
17332
17333        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17334            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17335            return;
17336        }
17337
17338        if (PackageManagerServiceUtils.isApkVerityEnabled()) {
17339            String apkPath = null;
17340            synchronized (mPackages) {
17341                // Note that if the attacker managed to skip verify setup, for example by tampering
17342                // with the package settings, upon reboot we will do full apk verification when
17343                // verity is not detected.
17344                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17345                if (ps != null && ps.isPrivileged()) {
17346                    apkPath = pkg.baseCodePath;
17347                }
17348            }
17349
17350            if (apkPath != null) {
17351                final VerityUtils.SetupResult result =
17352                        VerityUtils.generateApkVeritySetupData(apkPath);
17353                if (result.isOk()) {
17354                    if (Build.IS_DEBUGGABLE) Slog.i(TAG, "Enabling apk verity to " + apkPath);
17355                    FileDescriptor fd = result.getUnownedFileDescriptor();
17356                    try {
17357                        final byte[] signedRootHash = VerityUtils.generateFsverityRootHash(apkPath);
17358                        mInstaller.installApkVerity(apkPath, fd, result.getContentSize());
17359                        mInstaller.assertFsverityRootHashMatches(apkPath, signedRootHash);
17360                    } catch (InstallerException | IOException | DigestException |
17361                             NoSuchAlgorithmException e) {
17362                        res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17363                                "Failed to set up verity: " + e);
17364                        return;
17365                    } finally {
17366                        IoUtils.closeQuietly(fd);
17367                    }
17368                } else if (result.isFailed()) {
17369                    res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Failed to generate verity");
17370                    return;
17371                } else {
17372                    // Do nothing if verity is skipped. Will fall back to full apk verification on
17373                    // reboot.
17374                }
17375            }
17376        }
17377
17378        if (!instantApp) {
17379            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17380        } else {
17381            if (DEBUG_DOMAIN_VERIFICATION) {
17382                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
17383            }
17384        }
17385
17386        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17387                "installPackageLI")) {
17388            if (replace) {
17389                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17390                    // Static libs have a synthetic package name containing the version
17391                    // and cannot be updated as an update would get a new package name,
17392                    // unless this is the exact same version code which is useful for
17393                    // development.
17394                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17395                    if (existingPkg != null &&
17396                            existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) {
17397                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17398                                + "static-shared libs cannot be updated");
17399                        return;
17400                    }
17401                }
17402                replacePackageLIF(pkg, parseFlags, scanFlags, args.user,
17403                        installerPackageName, res, args.installReason);
17404            } else {
17405                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17406                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17407            }
17408        }
17409
17410        // Prepare the application profiles for the new code paths.
17411        // This needs to be done before invoking dexopt so that any install-time profile
17412        // can be used for optimizations.
17413        mArtManagerService.prepareAppProfiles(pkg, resolveUserIds(args.user.getIdentifier()));
17414
17415        // Check whether we need to dexopt the app.
17416        //
17417        // NOTE: it is IMPORTANT to call dexopt:
17418        //   - after doRename which will sync the package data from PackageParser.Package and its
17419        //     corresponding ApplicationInfo.
17420        //   - after installNewPackageLIF or replacePackageLIF which will update result with the
17421        //     uid of the application (pkg.applicationInfo.uid).
17422        //     This update happens in place!
17423        //
17424        // We only need to dexopt if the package meets ALL of the following conditions:
17425        //   1) it is not forward locked.
17426        //   2) it is not on on an external ASEC container.
17427        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
17428        //
17429        // Note that we do not dexopt instant apps by default. dexopt can take some time to
17430        // complete, so we skip this step during installation. Instead, we'll take extra time
17431        // the first time the instant app starts. It's preferred to do it this way to provide
17432        // continuous progress to the useur instead of mysteriously blocking somewhere in the
17433        // middle of running an instant app. The default behaviour can be overridden
17434        // via gservices.
17435        final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED)
17436                && !forwardLocked
17437                && !pkg.applicationInfo.isExternalAsec()
17438                && (!instantApp || Global.getInt(mContext.getContentResolver(),
17439                Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
17440
17441        if (performDexopt) {
17442            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17443            // Do not run PackageDexOptimizer through the local performDexOpt
17444            // method because `pkg` may not be in `mPackages` yet.
17445            //
17446            // Also, don't fail application installs if the dexopt step fails.
17447            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
17448                    REASON_INSTALL,
17449                    DexoptOptions.DEXOPT_BOOT_COMPLETE |
17450                    DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE);
17451            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17452                    null /* instructionSets */,
17453                    getOrCreateCompilerPackageStats(pkg),
17454                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
17455                    dexoptOptions);
17456            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17457        }
17458
17459        // Notify BackgroundDexOptService that the package has been changed.
17460        // If this is an update of a package which used to fail to compile,
17461        // BackgroundDexOptService will remove it from its blacklist.
17462        // TODO: Layering violation
17463        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17464
17465        synchronized (mPackages) {
17466            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17467            if (ps != null) {
17468                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17469                ps.setUpdateAvailable(false /*updateAvailable*/);
17470            }
17471
17472            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17473            for (int i = 0; i < childCount; i++) {
17474                PackageParser.Package childPkg = pkg.childPackages.get(i);
17475                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17476                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17477                if (childPs != null) {
17478                    childRes.newUsers = childPs.queryInstalledUsers(
17479                            sUserManager.getUserIds(), true);
17480                }
17481            }
17482
17483            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17484                updateSequenceNumberLP(ps, res.newUsers);
17485                updateInstantAppInstallerLocked(pkgName);
17486            }
17487        }
17488    }
17489
17490    private void startIntentFilterVerifications(int userId, boolean replacing,
17491            PackageParser.Package pkg) {
17492        if (mIntentFilterVerifierComponent == null) {
17493            Slog.w(TAG, "No IntentFilter verification will not be done as "
17494                    + "there is no IntentFilterVerifier available!");
17495            return;
17496        }
17497
17498        final int verifierUid = getPackageUid(
17499                mIntentFilterVerifierComponent.getPackageName(),
17500                MATCH_DEBUG_TRIAGED_MISSING,
17501                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17502
17503        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17504        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17505        mHandler.sendMessage(msg);
17506
17507        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17508        for (int i = 0; i < childCount; i++) {
17509            PackageParser.Package childPkg = pkg.childPackages.get(i);
17510            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17511            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17512            mHandler.sendMessage(msg);
17513        }
17514    }
17515
17516    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17517            PackageParser.Package pkg) {
17518        int size = pkg.activities.size();
17519        if (size == 0) {
17520            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17521                    "No activity, so no need to verify any IntentFilter!");
17522            return;
17523        }
17524
17525        final boolean hasDomainURLs = hasDomainURLs(pkg);
17526        if (!hasDomainURLs) {
17527            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17528                    "No domain URLs, so no need to verify any IntentFilter!");
17529            return;
17530        }
17531
17532        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17533                + " if any IntentFilter from the " + size
17534                + " Activities needs verification ...");
17535
17536        int count = 0;
17537        final String packageName = pkg.packageName;
17538
17539        synchronized (mPackages) {
17540            // If this is a new install and we see that we've already run verification for this
17541            // package, we have nothing to do: it means the state was restored from backup.
17542            if (!replacing) {
17543                IntentFilterVerificationInfo ivi =
17544                        mSettings.getIntentFilterVerificationLPr(packageName);
17545                if (ivi != null) {
17546                    if (DEBUG_DOMAIN_VERIFICATION) {
17547                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17548                                + ivi.getStatusString());
17549                    }
17550                    return;
17551                }
17552            }
17553
17554            // If any filters need to be verified, then all need to be.
17555            boolean needToVerify = false;
17556            for (PackageParser.Activity a : pkg.activities) {
17557                for (ActivityIntentInfo filter : a.intents) {
17558                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17559                        if (DEBUG_DOMAIN_VERIFICATION) {
17560                            Slog.d(TAG,
17561                                    "Intent filter needs verification, so processing all filters");
17562                        }
17563                        needToVerify = true;
17564                        break;
17565                    }
17566                }
17567            }
17568
17569            if (needToVerify) {
17570                final int verificationId = mIntentFilterVerificationToken++;
17571                for (PackageParser.Activity a : pkg.activities) {
17572                    for (ActivityIntentInfo filter : a.intents) {
17573                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17574                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17575                                    "Verification needed for IntentFilter:" + filter.toString());
17576                            mIntentFilterVerifier.addOneIntentFilterVerification(
17577                                    verifierUid, userId, verificationId, filter, packageName);
17578                            count++;
17579                        }
17580                    }
17581                }
17582            }
17583        }
17584
17585        if (count > 0) {
17586            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17587                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17588                    +  " for userId:" + userId);
17589            mIntentFilterVerifier.startVerifications(userId);
17590        } else {
17591            if (DEBUG_DOMAIN_VERIFICATION) {
17592                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17593            }
17594        }
17595    }
17596
17597    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17598        final ComponentName cn  = filter.activity.getComponentName();
17599        final String packageName = cn.getPackageName();
17600
17601        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17602                packageName);
17603        if (ivi == null) {
17604            return true;
17605        }
17606        int status = ivi.getStatus();
17607        switch (status) {
17608            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17609            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17610                return true;
17611
17612            default:
17613                // Nothing to do
17614                return false;
17615        }
17616    }
17617
17618    private static boolean isMultiArch(ApplicationInfo info) {
17619        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17620    }
17621
17622    private static boolean isExternal(PackageParser.Package pkg) {
17623        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17624    }
17625
17626    private static boolean isExternal(PackageSetting ps) {
17627        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17628    }
17629
17630    private static boolean isSystemApp(PackageParser.Package pkg) {
17631        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17632    }
17633
17634    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17635        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17636    }
17637
17638    private static boolean isOemApp(PackageParser.Package pkg) {
17639        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17640    }
17641
17642    private static boolean isVendorApp(PackageParser.Package pkg) {
17643        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
17644    }
17645
17646    private static boolean isProductApp(PackageParser.Package pkg) {
17647        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
17648    }
17649
17650    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17651        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17652    }
17653
17654    private static boolean isSystemApp(PackageSetting ps) {
17655        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17656    }
17657
17658    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17659        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17660    }
17661
17662    private int packageFlagsToInstallFlags(PackageSetting ps) {
17663        int installFlags = 0;
17664        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17665            // This existing package was an external ASEC install when we have
17666            // the external flag without a UUID
17667            installFlags |= PackageManager.INSTALL_EXTERNAL;
17668        }
17669        if (ps.isForwardLocked()) {
17670            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17671        }
17672        return installFlags;
17673    }
17674
17675    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17676        if (isExternal(pkg)) {
17677            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17678                return mSettings.getExternalVersion();
17679            } else {
17680                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17681            }
17682        } else {
17683            return mSettings.getInternalVersion();
17684        }
17685    }
17686
17687    private void deleteTempPackageFiles() {
17688        final FilenameFilter filter = new FilenameFilter() {
17689            public boolean accept(File dir, String name) {
17690                return name.startsWith("vmdl") && name.endsWith(".tmp");
17691            }
17692        };
17693        for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) {
17694            file.delete();
17695        }
17696    }
17697
17698    @Override
17699    public void deletePackageAsUser(String packageName, int versionCode,
17700            IPackageDeleteObserver observer, int userId, int flags) {
17701        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17702                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17703    }
17704
17705    @Override
17706    public void deletePackageVersioned(VersionedPackage versionedPackage,
17707            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17708        final int callingUid = Binder.getCallingUid();
17709        mContext.enforceCallingOrSelfPermission(
17710                android.Manifest.permission.DELETE_PACKAGES, null);
17711        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
17712        Preconditions.checkNotNull(versionedPackage);
17713        Preconditions.checkNotNull(observer);
17714        Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(),
17715                PackageManager.VERSION_CODE_HIGHEST,
17716                Long.MAX_VALUE, "versionCode must be >= -1");
17717
17718        final String packageName = versionedPackage.getPackageName();
17719        final long versionCode = versionedPackage.getLongVersionCode();
17720        final String internalPackageName;
17721        synchronized (mPackages) {
17722            // Normalize package name to handle renamed packages and static libs
17723            internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode);
17724        }
17725
17726        final int uid = Binder.getCallingUid();
17727        if (!isOrphaned(internalPackageName)
17728                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17729            try {
17730                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17731                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17732                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17733                observer.onUserActionRequired(intent);
17734            } catch (RemoteException re) {
17735            }
17736            return;
17737        }
17738        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17739        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17740        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17741            mContext.enforceCallingOrSelfPermission(
17742                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17743                    "deletePackage for user " + userId);
17744        }
17745
17746        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17747            try {
17748                observer.onPackageDeleted(packageName,
17749                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17750            } catch (RemoteException re) {
17751            }
17752            return;
17753        }
17754
17755        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17756            try {
17757                observer.onPackageDeleted(packageName,
17758                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17759            } catch (RemoteException re) {
17760            }
17761            return;
17762        }
17763
17764        if (DEBUG_REMOVE) {
17765            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17766                    + " deleteAllUsers: " + deleteAllUsers + " version="
17767                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17768                    ? "VERSION_CODE_HIGHEST" : versionCode));
17769        }
17770        // Queue up an async operation since the package deletion may take a little while.
17771        mHandler.post(new Runnable() {
17772            public void run() {
17773                mHandler.removeCallbacks(this);
17774                int returnCode;
17775                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
17776                boolean doDeletePackage = true;
17777                if (ps != null) {
17778                    final boolean targetIsInstantApp =
17779                            ps.getInstantApp(UserHandle.getUserId(callingUid));
17780                    doDeletePackage = !targetIsInstantApp
17781                            || canViewInstantApps;
17782                }
17783                if (doDeletePackage) {
17784                    if (!deleteAllUsers) {
17785                        returnCode = deletePackageX(internalPackageName, versionCode,
17786                                userId, deleteFlags);
17787                    } else {
17788                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
17789                                internalPackageName, users);
17790                        // If nobody is blocking uninstall, proceed with delete for all users
17791                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17792                            returnCode = deletePackageX(internalPackageName, versionCode,
17793                                    userId, deleteFlags);
17794                        } else {
17795                            // Otherwise uninstall individually for users with blockUninstalls=false
17796                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17797                            for (int userId : users) {
17798                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17799                                    returnCode = deletePackageX(internalPackageName, versionCode,
17800                                            userId, userFlags);
17801                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17802                                        Slog.w(TAG, "Package delete failed for user " + userId
17803                                                + ", returnCode " + returnCode);
17804                                    }
17805                                }
17806                            }
17807                            // The app has only been marked uninstalled for certain users.
17808                            // We still need to report that delete was blocked
17809                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17810                        }
17811                    }
17812                } else {
17813                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17814                }
17815                try {
17816                    observer.onPackageDeleted(packageName, returnCode, null);
17817                } catch (RemoteException e) {
17818                    Log.i(TAG, "Observer no longer exists.");
17819                } //end catch
17820            } //end run
17821        });
17822    }
17823
17824    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17825        if (pkg.staticSharedLibName != null) {
17826            return pkg.manifestPackageName;
17827        }
17828        return pkg.packageName;
17829    }
17830
17831    private String resolveInternalPackageNameLPr(String packageName, long versionCode) {
17832        // Handle renamed packages
17833        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17834        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17835
17836        // Is this a static library?
17837        LongSparseArray<SharedLibraryEntry> versionedLib =
17838                mStaticLibsByDeclaringPackage.get(packageName);
17839        if (versionedLib == null || versionedLib.size() <= 0) {
17840            return packageName;
17841        }
17842
17843        // Figure out which lib versions the caller can see
17844        LongSparseLongArray versionsCallerCanSee = null;
17845        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17846        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17847                && callingAppId != Process.ROOT_UID) {
17848            versionsCallerCanSee = new LongSparseLongArray();
17849            String libName = versionedLib.valueAt(0).info.getName();
17850            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17851            if (uidPackages != null) {
17852                for (String uidPackage : uidPackages) {
17853                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17854                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17855                    if (libIdx >= 0) {
17856                        final long libVersion = ps.usesStaticLibrariesVersions[libIdx];
17857                        versionsCallerCanSee.append(libVersion, libVersion);
17858                    }
17859                }
17860            }
17861        }
17862
17863        // Caller can see nothing - done
17864        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17865            return packageName;
17866        }
17867
17868        // Find the version the caller can see and the app version code
17869        SharedLibraryEntry highestVersion = null;
17870        final int versionCount = versionedLib.size();
17871        for (int i = 0; i < versionCount; i++) {
17872            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17873            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17874                    libEntry.info.getLongVersion()) < 0) {
17875                continue;
17876            }
17877            final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode();
17878            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17879                if (libVersionCode == versionCode) {
17880                    return libEntry.apk;
17881                }
17882            } else if (highestVersion == null) {
17883                highestVersion = libEntry;
17884            } else if (libVersionCode  > highestVersion.info
17885                    .getDeclaringPackage().getLongVersionCode()) {
17886                highestVersion = libEntry;
17887            }
17888        }
17889
17890        if (highestVersion != null) {
17891            return highestVersion.apk;
17892        }
17893
17894        return packageName;
17895    }
17896
17897    boolean isCallerVerifier(int callingUid) {
17898        final int callingUserId = UserHandle.getUserId(callingUid);
17899        return mRequiredVerifierPackage != null &&
17900                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
17901    }
17902
17903    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17904        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17905              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17906            return true;
17907        }
17908        final int callingUserId = UserHandle.getUserId(callingUid);
17909        // If the caller installed the pkgName, then allow it to silently uninstall.
17910        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17911            return true;
17912        }
17913
17914        // Allow package verifier to silently uninstall.
17915        if (mRequiredVerifierPackage != null &&
17916                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17917            return true;
17918        }
17919
17920        // Allow package uninstaller to silently uninstall.
17921        if (mRequiredUninstallerPackage != null &&
17922                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17923            return true;
17924        }
17925
17926        // Allow storage manager to silently uninstall.
17927        if (mStorageManagerPackage != null &&
17928                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17929            return true;
17930        }
17931
17932        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
17933        // uninstall for device owner provisioning.
17934        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
17935                == PERMISSION_GRANTED) {
17936            return true;
17937        }
17938
17939        return false;
17940    }
17941
17942    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17943        int[] result = EMPTY_INT_ARRAY;
17944        for (int userId : userIds) {
17945            if (getBlockUninstallForUser(packageName, userId)) {
17946                result = ArrayUtils.appendInt(result, userId);
17947            }
17948        }
17949        return result;
17950    }
17951
17952    @Override
17953    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17954        final int callingUid = Binder.getCallingUid();
17955        if (getInstantAppPackageName(callingUid) != null
17956                && !isCallerSameApp(packageName, callingUid)) {
17957            return false;
17958        }
17959        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17960    }
17961
17962    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17963        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17964                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17965        try {
17966            if (dpm != null) {
17967                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17968                        /* callingUserOnly =*/ false);
17969                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17970                        : deviceOwnerComponentName.getPackageName();
17971                // Does the package contains the device owner?
17972                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17973                // this check is probably not needed, since DO should be registered as a device
17974                // admin on some user too. (Original bug for this: b/17657954)
17975                if (packageName.equals(deviceOwnerPackageName)) {
17976                    return true;
17977                }
17978                // Does it contain a device admin for any user?
17979                int[] users;
17980                if (userId == UserHandle.USER_ALL) {
17981                    users = sUserManager.getUserIds();
17982                } else {
17983                    users = new int[]{userId};
17984                }
17985                for (int i = 0; i < users.length; ++i) {
17986                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17987                        return true;
17988                    }
17989                }
17990            }
17991        } catch (RemoteException e) {
17992        }
17993        return false;
17994    }
17995
17996    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17997        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17998    }
17999
18000    /**
18001     *  This method is an internal method that could be get invoked either
18002     *  to delete an installed package or to clean up a failed installation.
18003     *  After deleting an installed package, a broadcast is sent to notify any
18004     *  listeners that the package has been removed. For cleaning up a failed
18005     *  installation, the broadcast is not necessary since the package's
18006     *  installation wouldn't have sent the initial broadcast either
18007     *  The key steps in deleting a package are
18008     *  deleting the package information in internal structures like mPackages,
18009     *  deleting the packages base directories through installd
18010     *  updating mSettings to reflect current status
18011     *  persisting settings for later use
18012     *  sending a broadcast if necessary
18013     */
18014    int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) {
18015        final PackageRemovedInfo info = new PackageRemovedInfo(this);
18016        final boolean res;
18017
18018        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18019                ? UserHandle.USER_ALL : userId;
18020
18021        if (isPackageDeviceAdmin(packageName, removeUser)) {
18022            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18023            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18024        }
18025
18026        PackageSetting uninstalledPs = null;
18027        PackageParser.Package pkg = null;
18028
18029        // for the uninstall-updates case and restricted profiles, remember the per-
18030        // user handle installed state
18031        int[] allUsers;
18032        synchronized (mPackages) {
18033            uninstalledPs = mSettings.mPackages.get(packageName);
18034            if (uninstalledPs == null) {
18035                Slog.w(TAG, "Not removing non-existent package " + packageName);
18036                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18037            }
18038
18039            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18040                    && uninstalledPs.versionCode != versionCode) {
18041                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18042                        + uninstalledPs.versionCode + " != " + versionCode);
18043                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18044            }
18045
18046            // Static shared libs can be declared by any package, so let us not
18047            // allow removing a package if it provides a lib others depend on.
18048            pkg = mPackages.get(packageName);
18049
18050            allUsers = sUserManager.getUserIds();
18051
18052            if (pkg != null && pkg.staticSharedLibName != null) {
18053                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18054                        pkg.staticSharedLibVersion);
18055                if (libEntry != null) {
18056                    for (int currUserId : allUsers) {
18057                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18058                            continue;
18059                        }
18060                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18061                                libEntry.info, 0, currUserId);
18062                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18063                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18064                                    + " hosting lib " + libEntry.info.getName() + " version "
18065                                    + libEntry.info.getLongVersion() + " used by " + libClientPackages
18066                                    + " for user " + currUserId);
18067                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18068                        }
18069                    }
18070                }
18071            }
18072
18073            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18074        }
18075
18076        final int freezeUser;
18077        if (isUpdatedSystemApp(uninstalledPs)
18078                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18079            // We're downgrading a system app, which will apply to all users, so
18080            // freeze them all during the downgrade
18081            freezeUser = UserHandle.USER_ALL;
18082        } else {
18083            freezeUser = removeUser;
18084        }
18085
18086        synchronized (mInstallLock) {
18087            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18088            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18089                    deleteFlags, "deletePackageX")) {
18090                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18091                        deleteFlags | PackageManager.DELETE_CHATTY, info, true, null);
18092            }
18093            synchronized (mPackages) {
18094                if (res) {
18095                    if (pkg != null) {
18096                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18097                    }
18098                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18099                    updateInstantAppInstallerLocked(packageName);
18100                }
18101            }
18102        }
18103
18104        if (res) {
18105            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18106            info.sendPackageRemovedBroadcasts(killApp);
18107            info.sendSystemPackageUpdatedBroadcasts();
18108            info.sendSystemPackageAppearedBroadcasts();
18109        }
18110        // Force a gc here.
18111        Runtime.getRuntime().gc();
18112        // Delete the resources here after sending the broadcast to let
18113        // other processes clean up before deleting resources.
18114        if (info.args != null) {
18115            synchronized (mInstallLock) {
18116                info.args.doPostDeleteLI(true);
18117            }
18118        }
18119
18120        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18121    }
18122
18123    static class PackageRemovedInfo {
18124        final PackageSender packageSender;
18125        String removedPackage;
18126        String installerPackageName;
18127        int uid = -1;
18128        int removedAppId = -1;
18129        int[] origUsers;
18130        int[] removedUsers = null;
18131        int[] broadcastUsers = null;
18132        int[] instantUserIds = null;
18133        SparseArray<Integer> installReasons;
18134        boolean isRemovedPackageSystemUpdate = false;
18135        boolean isUpdate;
18136        boolean dataRemoved;
18137        boolean removedForAllUsers;
18138        boolean isStaticSharedLib;
18139        // Clean up resources deleted packages.
18140        InstallArgs args = null;
18141        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18142        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18143
18144        PackageRemovedInfo(PackageSender packageSender) {
18145            this.packageSender = packageSender;
18146        }
18147
18148        void sendPackageRemovedBroadcasts(boolean killApp) {
18149            sendPackageRemovedBroadcastInternal(killApp);
18150            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18151            for (int i = 0; i < childCount; i++) {
18152                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18153                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18154            }
18155        }
18156
18157        void sendSystemPackageUpdatedBroadcasts() {
18158            if (isRemovedPackageSystemUpdate) {
18159                sendSystemPackageUpdatedBroadcastsInternal();
18160                final int childCount = (removedChildPackages != null)
18161                        ? removedChildPackages.size() : 0;
18162                for (int i = 0; i < childCount; i++) {
18163                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18164                    if (childInfo.isRemovedPackageSystemUpdate) {
18165                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18166                    }
18167                }
18168            }
18169        }
18170
18171        void sendSystemPackageAppearedBroadcasts() {
18172            final int packageCount = (appearedChildPackages != null)
18173                    ? appearedChildPackages.size() : 0;
18174            for (int i = 0; i < packageCount; i++) {
18175                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18176                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18177                    true /*sendBootCompleted*/, false /*startReceiver*/,
18178                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null);
18179            }
18180        }
18181
18182        private void sendSystemPackageUpdatedBroadcastsInternal() {
18183            Bundle extras = new Bundle(2);
18184            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18185            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18186            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18187                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18188            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18189                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18190            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18191                null, null, 0, removedPackage, null, null, null);
18192            if (installerPackageName != null) {
18193                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18194                        removedPackage, extras, 0 /*flags*/,
18195                        installerPackageName, null, null, null);
18196                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18197                        removedPackage, extras, 0 /*flags*/,
18198                        installerPackageName, null, null, null);
18199            }
18200        }
18201
18202        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18203            // Don't send static shared library removal broadcasts as these
18204            // libs are visible only the the apps that depend on them an one
18205            // cannot remove the library if it has a dependency.
18206            if (isStaticSharedLib) {
18207                return;
18208            }
18209            Bundle extras = new Bundle(2);
18210            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18211            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18212            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18213            if (isUpdate || isRemovedPackageSystemUpdate) {
18214                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18215            }
18216            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18217            if (removedPackage != null) {
18218                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18219                    removedPackage, extras, 0, null /*targetPackage*/, null,
18220                    broadcastUsers, instantUserIds);
18221                if (installerPackageName != null) {
18222                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18223                            removedPackage, extras, 0 /*flags*/,
18224                            installerPackageName, null, broadcastUsers, instantUserIds);
18225                }
18226                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18227                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18228                        removedPackage, extras,
18229                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18230                        null, null, broadcastUsers, instantUserIds);
18231                    packageSender.notifyPackageRemoved(removedPackage);
18232                }
18233            }
18234            if (removedAppId >= 0) {
18235                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
18236                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18237                    null, null, broadcastUsers, instantUserIds);
18238            }
18239        }
18240
18241        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18242            removedUsers = userIds;
18243            if (removedUsers == null) {
18244                broadcastUsers = null;
18245                return;
18246            }
18247
18248            broadcastUsers = EMPTY_INT_ARRAY;
18249            instantUserIds = EMPTY_INT_ARRAY;
18250            for (int i = userIds.length - 1; i >= 0; --i) {
18251                final int userId = userIds[i];
18252                if (deletedPackageSetting.getInstantApp(userId)) {
18253                    instantUserIds = ArrayUtils.appendInt(instantUserIds, userId);
18254                } else {
18255                    broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18256                }
18257            }
18258        }
18259    }
18260
18261    /*
18262     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18263     * flag is not set, the data directory is removed as well.
18264     * make sure this flag is set for partially installed apps. If not its meaningless to
18265     * delete a partially installed application.
18266     */
18267    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18268            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18269        String packageName = ps.name;
18270        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18271        // Retrieve object to delete permissions for shared user later on
18272        final PackageParser.Package deletedPkg;
18273        final PackageSetting deletedPs;
18274        // reader
18275        synchronized (mPackages) {
18276            deletedPkg = mPackages.get(packageName);
18277            deletedPs = mSettings.mPackages.get(packageName);
18278            if (outInfo != null) {
18279                outInfo.removedPackage = packageName;
18280                outInfo.installerPackageName = ps.installerPackageName;
18281                outInfo.isStaticSharedLib = deletedPkg != null
18282                        && deletedPkg.staticSharedLibName != null;
18283                outInfo.populateUsers(deletedPs == null ? null
18284                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18285            }
18286        }
18287
18288        removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0);
18289
18290        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18291            final PackageParser.Package resolvedPkg;
18292            if (deletedPkg != null) {
18293                resolvedPkg = deletedPkg;
18294            } else {
18295                // We don't have a parsed package when it lives on an ejected
18296                // adopted storage device, so fake something together
18297                resolvedPkg = new PackageParser.Package(ps.name);
18298                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18299            }
18300            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18301                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18302            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18303            if (outInfo != null) {
18304                outInfo.dataRemoved = true;
18305            }
18306            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18307        }
18308
18309        int removedAppId = -1;
18310
18311        // writer
18312        synchronized (mPackages) {
18313            boolean installedStateChanged = false;
18314            if (deletedPs != null) {
18315                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18316                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18317                    clearDefaultBrowserIfNeeded(packageName);
18318                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18319                    removedAppId = mSettings.removePackageLPw(packageName);
18320                    if (outInfo != null) {
18321                        outInfo.removedAppId = removedAppId;
18322                    }
18323                    mPermissionManager.updatePermissions(
18324                            deletedPs.name, null, false, mPackages.values(), mPermissionCallback);
18325                    if (deletedPs.sharedUser != null) {
18326                        // Remove permissions associated with package. Since runtime
18327                        // permissions are per user we have to kill the removed package
18328                        // or packages running under the shared user of the removed
18329                        // package if revoking the permissions requested only by the removed
18330                        // package is successful and this causes a change in gids.
18331                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18332                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18333                                    userId);
18334                            if (userIdToKill == UserHandle.USER_ALL
18335                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18336                                // If gids changed for this user, kill all affected packages.
18337                                mHandler.post(new Runnable() {
18338                                    @Override
18339                                    public void run() {
18340                                        // This has to happen with no lock held.
18341                                        killApplication(deletedPs.name, deletedPs.appId,
18342                                                KILL_APP_REASON_GIDS_CHANGED);
18343                                    }
18344                                });
18345                                break;
18346                            }
18347                        }
18348                    }
18349                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18350                }
18351                // make sure to preserve per-user disabled state if this removal was just
18352                // a downgrade of a system app to the factory package
18353                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18354                    if (DEBUG_REMOVE) {
18355                        Slog.d(TAG, "Propagating install state across downgrade");
18356                    }
18357                    for (int userId : allUserHandles) {
18358                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18359                        if (DEBUG_REMOVE) {
18360                            Slog.d(TAG, "    user " + userId + " => " + installed);
18361                        }
18362                        if (installed != ps.getInstalled(userId)) {
18363                            installedStateChanged = true;
18364                        }
18365                        ps.setInstalled(installed, userId);
18366                    }
18367                }
18368            }
18369            // can downgrade to reader
18370            if (writeSettings) {
18371                // Save settings now
18372                mSettings.writeLPr();
18373            }
18374            if (installedStateChanged) {
18375                mSettings.writeKernelMappingLPr(ps);
18376            }
18377        }
18378        if (removedAppId != -1) {
18379            // A user ID was deleted here. Go through all users and remove it
18380            // from KeyStore.
18381            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18382        }
18383    }
18384
18385    static boolean locationIsPrivileged(String path) {
18386        try {
18387            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
18388            final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
18389            final File privilegedOdmAppDir = new File(Environment.getOdmDirectory(), "priv-app");
18390            final File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
18391            return path.startsWith(privilegedAppDir.getCanonicalPath())
18392                    || path.startsWith(privilegedVendorAppDir.getCanonicalPath())
18393                    || path.startsWith(privilegedOdmAppDir.getCanonicalPath())
18394                    || path.startsWith(privilegedProductAppDir.getCanonicalPath());
18395        } catch (IOException e) {
18396            Slog.e(TAG, "Unable to access code path " + path);
18397        }
18398        return false;
18399    }
18400
18401    static boolean locationIsOem(String path) {
18402        try {
18403            return path.startsWith(Environment.getOemDirectory().getCanonicalPath());
18404        } catch (IOException e) {
18405            Slog.e(TAG, "Unable to access code path " + path);
18406        }
18407        return false;
18408    }
18409
18410    static boolean locationIsVendor(String path) {
18411        try {
18412            return path.startsWith(Environment.getVendorDirectory().getCanonicalPath())
18413                    || path.startsWith(Environment.getOdmDirectory().getCanonicalPath());
18414        } catch (IOException e) {
18415            Slog.e(TAG, "Unable to access code path " + path);
18416        }
18417        return false;
18418    }
18419
18420    static boolean locationIsProduct(String path) {
18421        try {
18422            return path.startsWith(Environment.getProductDirectory().getCanonicalPath());
18423        } catch (IOException e) {
18424            Slog.e(TAG, "Unable to access code path " + path);
18425        }
18426        return false;
18427    }
18428
18429    /*
18430     * Tries to delete system package.
18431     */
18432    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18433            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18434            boolean writeSettings) {
18435        if (deletedPs.parentPackageName != null) {
18436            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18437            return false;
18438        }
18439
18440        final boolean applyUserRestrictions
18441                = (allUserHandles != null) && (outInfo.origUsers != null);
18442        final PackageSetting disabledPs;
18443        // Confirm if the system package has been updated
18444        // An updated system app can be deleted. This will also have to restore
18445        // the system pkg from system partition
18446        // reader
18447        synchronized (mPackages) {
18448            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18449        }
18450
18451        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18452                + " disabledPs=" + disabledPs);
18453
18454        if (disabledPs == null) {
18455            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18456            return false;
18457        } else if (DEBUG_REMOVE) {
18458            Slog.d(TAG, "Deleting system pkg from data partition");
18459        }
18460
18461        if (DEBUG_REMOVE) {
18462            if (applyUserRestrictions) {
18463                Slog.d(TAG, "Remembering install states:");
18464                for (int userId : allUserHandles) {
18465                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18466                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18467                }
18468            }
18469        }
18470
18471        // Delete the updated package
18472        outInfo.isRemovedPackageSystemUpdate = true;
18473        if (outInfo.removedChildPackages != null) {
18474            final int childCount = (deletedPs.childPackageNames != null)
18475                    ? deletedPs.childPackageNames.size() : 0;
18476            for (int i = 0; i < childCount; i++) {
18477                String childPackageName = deletedPs.childPackageNames.get(i);
18478                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18479                        .contains(childPackageName)) {
18480                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18481                            childPackageName);
18482                    if (childInfo != null) {
18483                        childInfo.isRemovedPackageSystemUpdate = true;
18484                    }
18485                }
18486            }
18487        }
18488
18489        if (disabledPs.versionCode < deletedPs.versionCode) {
18490            // Delete data for downgrades
18491            flags &= ~PackageManager.DELETE_KEEP_DATA;
18492        } else {
18493            // Preserve data by setting flag
18494            flags |= PackageManager.DELETE_KEEP_DATA;
18495        }
18496
18497        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18498                outInfo, writeSettings, disabledPs.pkg);
18499        if (!ret) {
18500            return false;
18501        }
18502
18503        // writer
18504        synchronized (mPackages) {
18505            // NOTE: The system package always needs to be enabled; even if it's for
18506            // a compressed stub. If we don't, installing the system package fails
18507            // during scan [scanning checks the disabled packages]. We will reverse
18508            // this later, after we've "installed" the stub.
18509            // Reinstate the old system package
18510            enableSystemPackageLPw(disabledPs.pkg);
18511            // Remove any native libraries from the upgraded package.
18512            removeNativeBinariesLI(deletedPs);
18513        }
18514
18515        // Install the system package
18516        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18517        try {
18518            installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles,
18519                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
18520        } catch (PackageManagerException e) {
18521            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18522                    + e.getMessage());
18523            return false;
18524        } finally {
18525            if (disabledPs.pkg.isStub) {
18526                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
18527            }
18528        }
18529        return true;
18530    }
18531
18532    /**
18533     * Installs a package that's already on the system partition.
18534     */
18535    private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString,
18536            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
18537            @Nullable PermissionsState origPermissionState, boolean writeSettings)
18538                    throws PackageManagerException {
18539        @ParseFlags int parseFlags =
18540                mDefParseFlags
18541                | PackageParser.PARSE_MUST_BE_APK
18542                | PackageParser.PARSE_IS_SYSTEM_DIR;
18543        @ScanFlags int scanFlags = SCAN_AS_SYSTEM;
18544        if (isPrivileged || locationIsPrivileged(codePathString)) {
18545            scanFlags |= SCAN_AS_PRIVILEGED;
18546        }
18547        if (locationIsOem(codePathString)) {
18548            scanFlags |= SCAN_AS_OEM;
18549        }
18550        if (locationIsVendor(codePathString)) {
18551            scanFlags |= SCAN_AS_VENDOR;
18552        }
18553        if (locationIsProduct(codePathString)) {
18554            scanFlags |= SCAN_AS_PRODUCT;
18555        }
18556
18557        final File codePath = new File(codePathString);
18558        final PackageParser.Package pkg =
18559                scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null);
18560
18561        try {
18562            // update shared libraries for the newly re-installed system package
18563            updateSharedLibrariesLPr(pkg, null);
18564        } catch (PackageManagerException e) {
18565            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18566        }
18567
18568        prepareAppDataAfterInstallLIF(pkg);
18569
18570        // writer
18571        synchronized (mPackages) {
18572            PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
18573
18574            // Propagate the permissions state as we do not want to drop on the floor
18575            // runtime permissions. The update permissions method below will take
18576            // care of removing obsolete permissions and grant install permissions.
18577            if (origPermissionState != null) {
18578                ps.getPermissionsState().copyFrom(origPermissionState);
18579            }
18580            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
18581                    mPermissionCallback);
18582
18583            final boolean applyUserRestrictions
18584                    = (allUserHandles != null) && (origUserHandles != null);
18585            if (applyUserRestrictions) {
18586                boolean installedStateChanged = false;
18587                if (DEBUG_REMOVE) {
18588                    Slog.d(TAG, "Propagating install state across reinstall");
18589                }
18590                for (int userId : allUserHandles) {
18591                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
18592                    if (DEBUG_REMOVE) {
18593                        Slog.d(TAG, "    user " + userId + " => " + installed);
18594                    }
18595                    if (installed != ps.getInstalled(userId)) {
18596                        installedStateChanged = true;
18597                    }
18598                    ps.setInstalled(installed, userId);
18599
18600                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18601                }
18602                // Regardless of writeSettings we need to ensure that this restriction
18603                // state propagation is persisted
18604                mSettings.writeAllUsersPackageRestrictionsLPr();
18605                if (installedStateChanged) {
18606                    mSettings.writeKernelMappingLPr(ps);
18607                }
18608            }
18609            // can downgrade to reader here
18610            if (writeSettings) {
18611                mSettings.writeLPr();
18612            }
18613        }
18614        return pkg;
18615    }
18616
18617    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18618            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18619            PackageRemovedInfo outInfo, boolean writeSettings,
18620            PackageParser.Package replacingPackage) {
18621        synchronized (mPackages) {
18622            if (outInfo != null) {
18623                outInfo.uid = ps.appId;
18624            }
18625
18626            if (outInfo != null && outInfo.removedChildPackages != null) {
18627                final int childCount = (ps.childPackageNames != null)
18628                        ? ps.childPackageNames.size() : 0;
18629                for (int i = 0; i < childCount; i++) {
18630                    String childPackageName = ps.childPackageNames.get(i);
18631                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18632                    if (childPs == null) {
18633                        return false;
18634                    }
18635                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18636                            childPackageName);
18637                    if (childInfo != null) {
18638                        childInfo.uid = childPs.appId;
18639                    }
18640                }
18641            }
18642        }
18643
18644        // Delete package data from internal structures and also remove data if flag is set
18645        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18646
18647        // Delete the child packages data
18648        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18649        for (int i = 0; i < childCount; i++) {
18650            PackageSetting childPs;
18651            synchronized (mPackages) {
18652                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18653            }
18654            if (childPs != null) {
18655                PackageRemovedInfo childOutInfo = (outInfo != null
18656                        && outInfo.removedChildPackages != null)
18657                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18658                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18659                        && (replacingPackage != null
18660                        && !replacingPackage.hasChildPackage(childPs.name))
18661                        ? flags & ~DELETE_KEEP_DATA : flags;
18662                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18663                        deleteFlags, writeSettings);
18664            }
18665        }
18666
18667        // Delete application code and resources only for parent packages
18668        if (ps.parentPackageName == null) {
18669            if (deleteCodeAndResources && (outInfo != null)) {
18670                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18671                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18672                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18673            }
18674        }
18675
18676        return true;
18677    }
18678
18679    @Override
18680    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18681            int userId) {
18682        mContext.enforceCallingOrSelfPermission(
18683                android.Manifest.permission.DELETE_PACKAGES, null);
18684        synchronized (mPackages) {
18685            // Cannot block uninstall of static shared libs as they are
18686            // considered a part of the using app (emulating static linking).
18687            // Also static libs are installed always on internal storage.
18688            PackageParser.Package pkg = mPackages.get(packageName);
18689            if (pkg != null && pkg.staticSharedLibName != null) {
18690                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18691                        + " providing static shared library: " + pkg.staticSharedLibName);
18692                return false;
18693            }
18694            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18695            mSettings.writePackageRestrictionsLPr(userId);
18696        }
18697        return true;
18698    }
18699
18700    @Override
18701    public boolean getBlockUninstallForUser(String packageName, int userId) {
18702        synchronized (mPackages) {
18703            final PackageSetting ps = mSettings.mPackages.get(packageName);
18704            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
18705                return false;
18706            }
18707            return mSettings.getBlockUninstallLPr(userId, packageName);
18708        }
18709    }
18710
18711    @Override
18712    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18713        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
18714        synchronized (mPackages) {
18715            PackageSetting ps = mSettings.mPackages.get(packageName);
18716            if (ps == null) {
18717                Log.w(TAG, "Package doesn't exist: " + packageName);
18718                return false;
18719            }
18720            if (systemUserApp) {
18721                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18722            } else {
18723                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18724            }
18725            mSettings.writeLPr();
18726        }
18727        return true;
18728    }
18729
18730    /*
18731     * This method handles package deletion in general
18732     */
18733    private boolean deletePackageLIF(String packageName, UserHandle user,
18734            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18735            PackageRemovedInfo outInfo, boolean writeSettings,
18736            PackageParser.Package replacingPackage) {
18737        if (packageName == null) {
18738            Slog.w(TAG, "Attempt to delete null packageName.");
18739            return false;
18740        }
18741
18742        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18743
18744        PackageSetting ps;
18745        synchronized (mPackages) {
18746            ps = mSettings.mPackages.get(packageName);
18747            if (ps == null) {
18748                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18749                return false;
18750            }
18751
18752            if (ps.parentPackageName != null && (!isSystemApp(ps)
18753                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18754                if (DEBUG_REMOVE) {
18755                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18756                            + ((user == null) ? UserHandle.USER_ALL : user));
18757                }
18758                final int removedUserId = (user != null) ? user.getIdentifier()
18759                        : UserHandle.USER_ALL;
18760
18761                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18762                    return false;
18763                }
18764                markPackageUninstalledForUserLPw(ps, user);
18765                scheduleWritePackageRestrictionsLocked(user);
18766                return true;
18767            }
18768        }
18769
18770        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
18771        if (ps.getPermissionsState().hasPermission(Manifest.permission.SUSPEND_APPS, userId)) {
18772            onSuspendingPackageRemoved(packageName, userId);
18773        }
18774
18775
18776        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18777                && user.getIdentifier() != UserHandle.USER_ALL)) {
18778            // The caller is asking that the package only be deleted for a single
18779            // user.  To do this, we just mark its uninstalled state and delete
18780            // its data. If this is a system app, we only allow this to happen if
18781            // they have set the special DELETE_SYSTEM_APP which requests different
18782            // semantics than normal for uninstalling system apps.
18783            markPackageUninstalledForUserLPw(ps, user);
18784
18785            if (!isSystemApp(ps)) {
18786                // Do not uninstall the APK if an app should be cached
18787                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18788                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18789                    // Other user still have this package installed, so all
18790                    // we need to do is clear this user's data and save that
18791                    // it is uninstalled.
18792                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18793                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18794                        return false;
18795                    }
18796                    scheduleWritePackageRestrictionsLocked(user);
18797                    return true;
18798                } else {
18799                    // We need to set it back to 'installed' so the uninstall
18800                    // broadcasts will be sent correctly.
18801                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18802                    ps.setInstalled(true, user.getIdentifier());
18803                    mSettings.writeKernelMappingLPr(ps);
18804                }
18805            } else {
18806                // This is a system app, so we assume that the
18807                // other users still have this package installed, so all
18808                // we need to do is clear this user's data and save that
18809                // it is uninstalled.
18810                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18811                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18812                    return false;
18813                }
18814                scheduleWritePackageRestrictionsLocked(user);
18815                return true;
18816            }
18817        }
18818
18819        // If we are deleting a composite package for all users, keep track
18820        // of result for each child.
18821        if (ps.childPackageNames != null && outInfo != null) {
18822            synchronized (mPackages) {
18823                final int childCount = ps.childPackageNames.size();
18824                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18825                for (int i = 0; i < childCount; i++) {
18826                    String childPackageName = ps.childPackageNames.get(i);
18827                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18828                    childInfo.removedPackage = childPackageName;
18829                    childInfo.installerPackageName = ps.installerPackageName;
18830                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18831                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18832                    if (childPs != null) {
18833                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18834                    }
18835                }
18836            }
18837        }
18838
18839        boolean ret = false;
18840        if (isSystemApp(ps)) {
18841            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18842            // When an updated system application is deleted we delete the existing resources
18843            // as well and fall back to existing code in system partition
18844            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18845        } else {
18846            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18847            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18848                    outInfo, writeSettings, replacingPackage);
18849        }
18850
18851        // Take a note whether we deleted the package for all users
18852        if (outInfo != null) {
18853            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18854            if (outInfo.removedChildPackages != null) {
18855                synchronized (mPackages) {
18856                    final int childCount = outInfo.removedChildPackages.size();
18857                    for (int i = 0; i < childCount; i++) {
18858                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18859                        if (childInfo != null) {
18860                            childInfo.removedForAllUsers = mPackages.get(
18861                                    childInfo.removedPackage) == null;
18862                        }
18863                    }
18864                }
18865            }
18866            // If we uninstalled an update to a system app there may be some
18867            // child packages that appeared as they are declared in the system
18868            // app but were not declared in the update.
18869            if (isSystemApp(ps)) {
18870                synchronized (mPackages) {
18871                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18872                    final int childCount = (updatedPs.childPackageNames != null)
18873                            ? updatedPs.childPackageNames.size() : 0;
18874                    for (int i = 0; i < childCount; i++) {
18875                        String childPackageName = updatedPs.childPackageNames.get(i);
18876                        if (outInfo.removedChildPackages == null
18877                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18878                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18879                            if (childPs == null) {
18880                                continue;
18881                            }
18882                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18883                            installRes.name = childPackageName;
18884                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18885                            installRes.pkg = mPackages.get(childPackageName);
18886                            installRes.uid = childPs.pkg.applicationInfo.uid;
18887                            if (outInfo.appearedChildPackages == null) {
18888                                outInfo.appearedChildPackages = new ArrayMap<>();
18889                            }
18890                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18891                        }
18892                    }
18893                }
18894            }
18895        }
18896
18897        return ret;
18898    }
18899
18900    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18901        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18902                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18903        for (int nextUserId : userIds) {
18904            if (DEBUG_REMOVE) {
18905                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18906            }
18907            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18908                    false /*installed*/,
18909                    true /*stopped*/,
18910                    true /*notLaunched*/,
18911                    false /*hidden*/,
18912                    false /*suspended*/,
18913                    null, /*suspendingPackage*/
18914                    null, /*suspendedAppExtras*/
18915                    null, /*suspendedLauncherExtras*/
18916                    false /*instantApp*/,
18917                    false /*virtualPreload*/,
18918                    null /*lastDisableAppCaller*/,
18919                    null /*enabledComponents*/,
18920                    null /*disabledComponents*/,
18921                    ps.readUserState(nextUserId).domainVerificationStatus,
18922                    0, PackageManager.INSTALL_REASON_UNKNOWN,
18923                    null /*harmfulAppWarning*/);
18924        }
18925        mSettings.writeKernelMappingLPr(ps);
18926    }
18927
18928    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18929            PackageRemovedInfo outInfo) {
18930        final PackageParser.Package pkg;
18931        synchronized (mPackages) {
18932            pkg = mPackages.get(ps.name);
18933        }
18934
18935        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18936                : new int[] {userId};
18937        for (int nextUserId : userIds) {
18938            if (DEBUG_REMOVE) {
18939                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18940                        + nextUserId);
18941            }
18942
18943            destroyAppDataLIF(pkg, userId,
18944                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18945            destroyAppProfilesLIF(pkg, userId);
18946            clearDefaultBrowserIfNeededForUser(ps.name, userId);
18947            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18948            schedulePackageCleaning(ps.name, nextUserId, false);
18949            synchronized (mPackages) {
18950                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18951                    scheduleWritePackageRestrictionsLocked(nextUserId);
18952                }
18953                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18954            }
18955        }
18956
18957        if (outInfo != null) {
18958            outInfo.removedPackage = ps.name;
18959            outInfo.installerPackageName = ps.installerPackageName;
18960            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18961            outInfo.removedAppId = ps.appId;
18962            outInfo.removedUsers = userIds;
18963            outInfo.broadcastUsers = userIds;
18964        }
18965
18966        return true;
18967    }
18968
18969    private final class ClearStorageConnection implements ServiceConnection {
18970        IMediaContainerService mContainerService;
18971
18972        @Override
18973        public void onServiceConnected(ComponentName name, IBinder service) {
18974            synchronized (this) {
18975                mContainerService = IMediaContainerService.Stub
18976                        .asInterface(Binder.allowBlocking(service));
18977                notifyAll();
18978            }
18979        }
18980
18981        @Override
18982        public void onServiceDisconnected(ComponentName name) {
18983        }
18984    }
18985
18986    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18987        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18988
18989        final boolean mounted;
18990        if (Environment.isExternalStorageEmulated()) {
18991            mounted = true;
18992        } else {
18993            final String status = Environment.getExternalStorageState();
18994
18995            mounted = status.equals(Environment.MEDIA_MOUNTED)
18996                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18997        }
18998
18999        if (!mounted) {
19000            return;
19001        }
19002
19003        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19004        int[] users;
19005        if (userId == UserHandle.USER_ALL) {
19006            users = sUserManager.getUserIds();
19007        } else {
19008            users = new int[] { userId };
19009        }
19010        final ClearStorageConnection conn = new ClearStorageConnection();
19011        if (mContext.bindServiceAsUser(
19012                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19013            try {
19014                for (int curUser : users) {
19015                    long timeout = SystemClock.uptimeMillis() + 5000;
19016                    synchronized (conn) {
19017                        long now;
19018                        while (conn.mContainerService == null &&
19019                                (now = SystemClock.uptimeMillis()) < timeout) {
19020                            try {
19021                                conn.wait(timeout - now);
19022                            } catch (InterruptedException e) {
19023                            }
19024                        }
19025                    }
19026                    if (conn.mContainerService == null) {
19027                        return;
19028                    }
19029
19030                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19031                    clearDirectory(conn.mContainerService,
19032                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19033                    if (allData) {
19034                        clearDirectory(conn.mContainerService,
19035                                userEnv.buildExternalStorageAppDataDirs(packageName));
19036                        clearDirectory(conn.mContainerService,
19037                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19038                    }
19039                }
19040            } finally {
19041                mContext.unbindService(conn);
19042            }
19043        }
19044    }
19045
19046    @Override
19047    public void clearApplicationProfileData(String packageName) {
19048        enforceSystemOrRoot("Only the system can clear all profile data");
19049
19050        final PackageParser.Package pkg;
19051        synchronized (mPackages) {
19052            pkg = mPackages.get(packageName);
19053        }
19054
19055        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19056            synchronized (mInstallLock) {
19057                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19058            }
19059        }
19060    }
19061
19062    @Override
19063    public void clearApplicationUserData(final String packageName,
19064            final IPackageDataObserver observer, final int userId) {
19065        mContext.enforceCallingOrSelfPermission(
19066                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19067
19068        final int callingUid = Binder.getCallingUid();
19069        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19070                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19071
19072        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19073        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
19074        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19075            throw new SecurityException("Cannot clear data for a protected package: "
19076                    + packageName);
19077        }
19078        // Queue up an async operation since the package deletion may take a little while.
19079        mHandler.post(new Runnable() {
19080            public void run() {
19081                mHandler.removeCallbacks(this);
19082                final boolean succeeded;
19083                if (!filterApp) {
19084                    try (PackageFreezer freezer = freezePackage(packageName,
19085                            "clearApplicationUserData")) {
19086                        synchronized (mInstallLock) {
19087                            succeeded = clearApplicationUserDataLIF(packageName, userId);
19088                        }
19089                        clearExternalStorageDataSync(packageName, userId, true);
19090                        synchronized (mPackages) {
19091                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19092                                    packageName, userId);
19093                        }
19094                    }
19095                    if (succeeded) {
19096                        // invoke DeviceStorageMonitor's update method to clear any notifications
19097                        DeviceStorageMonitorInternal dsm = LocalServices
19098                                .getService(DeviceStorageMonitorInternal.class);
19099                        if (dsm != null) {
19100                            dsm.checkMemory();
19101                        }
19102                    }
19103                } else {
19104                    succeeded = false;
19105                }
19106                if (observer != null) {
19107                    try {
19108                        observer.onRemoveCompleted(packageName, succeeded);
19109                    } catch (RemoteException e) {
19110                        Log.i(TAG, "Observer no longer exists.");
19111                    }
19112                } //end if observer
19113            } //end run
19114        });
19115    }
19116
19117    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19118        if (packageName == null) {
19119            Slog.w(TAG, "Attempt to delete null packageName.");
19120            return false;
19121        }
19122
19123        // Try finding details about the requested package
19124        PackageParser.Package pkg;
19125        synchronized (mPackages) {
19126            pkg = mPackages.get(packageName);
19127            if (pkg == null) {
19128                final PackageSetting ps = mSettings.mPackages.get(packageName);
19129                if (ps != null) {
19130                    pkg = ps.pkg;
19131                }
19132            }
19133
19134            if (pkg == null) {
19135                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19136                return false;
19137            }
19138
19139            PackageSetting ps = (PackageSetting) pkg.mExtras;
19140            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19141        }
19142
19143        clearAppDataLIF(pkg, userId,
19144                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19145
19146        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19147        removeKeystoreDataIfNeeded(userId, appId);
19148
19149        UserManagerInternal umInternal = getUserManagerInternal();
19150        final int flags;
19151        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19152            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19153        } else if (umInternal.isUserRunning(userId)) {
19154            flags = StorageManager.FLAG_STORAGE_DE;
19155        } else {
19156            flags = 0;
19157        }
19158        prepareAppDataContentsLIF(pkg, userId, flags);
19159
19160        return true;
19161    }
19162
19163    /**
19164     * Reverts user permission state changes (permissions and flags) in
19165     * all packages for a given user.
19166     *
19167     * @param userId The device user for which to do a reset.
19168     */
19169    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19170        final int packageCount = mPackages.size();
19171        for (int i = 0; i < packageCount; i++) {
19172            PackageParser.Package pkg = mPackages.valueAt(i);
19173            PackageSetting ps = (PackageSetting) pkg.mExtras;
19174            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19175        }
19176    }
19177
19178    private void resetNetworkPolicies(int userId) {
19179        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19180    }
19181
19182    /**
19183     * Reverts user permission state changes (permissions and flags).
19184     *
19185     * @param ps The package for which to reset.
19186     * @param userId The device user for which to do a reset.
19187     */
19188    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19189            final PackageSetting ps, final int userId) {
19190        if (ps.pkg == null) {
19191            return;
19192        }
19193
19194        // These are flags that can change base on user actions.
19195        final int userSettableMask = FLAG_PERMISSION_USER_SET
19196                | FLAG_PERMISSION_USER_FIXED
19197                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19198                | FLAG_PERMISSION_REVIEW_REQUIRED;
19199
19200        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19201                | FLAG_PERMISSION_POLICY_FIXED;
19202
19203        boolean writeInstallPermissions = false;
19204        boolean writeRuntimePermissions = false;
19205
19206        final int permissionCount = ps.pkg.requestedPermissions.size();
19207        for (int i = 0; i < permissionCount; i++) {
19208            final String permName = ps.pkg.requestedPermissions.get(i);
19209            final BasePermission bp =
19210                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
19211            if (bp == null) {
19212                continue;
19213            }
19214
19215            // If shared user we just reset the state to which only this app contributed.
19216            if (ps.sharedUser != null) {
19217                boolean used = false;
19218                final int packageCount = ps.sharedUser.packages.size();
19219                for (int j = 0; j < packageCount; j++) {
19220                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19221                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19222                            && pkg.pkg.requestedPermissions.contains(permName)) {
19223                        used = true;
19224                        break;
19225                    }
19226                }
19227                if (used) {
19228                    continue;
19229                }
19230            }
19231
19232            final PermissionsState permissionsState = ps.getPermissionsState();
19233
19234            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
19235
19236            // Always clear the user settable flags.
19237            final boolean hasInstallState =
19238                    permissionsState.getInstallPermissionState(permName) != null;
19239            // If permission review is enabled and this is a legacy app, mark the
19240            // permission as requiring a review as this is the initial state.
19241            int flags = 0;
19242            if (mSettings.mPermissions.mPermissionReviewRequired
19243                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19244                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19245            }
19246            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19247                if (hasInstallState) {
19248                    writeInstallPermissions = true;
19249                } else {
19250                    writeRuntimePermissions = true;
19251                }
19252            }
19253
19254            // Below is only runtime permission handling.
19255            if (!bp.isRuntime()) {
19256                continue;
19257            }
19258
19259            // Never clobber system or policy.
19260            if ((oldFlags & policyOrSystemFlags) != 0) {
19261                continue;
19262            }
19263
19264            // If this permission was granted by default, make sure it is.
19265            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19266                if (permissionsState.grantRuntimePermission(bp, userId)
19267                        != PERMISSION_OPERATION_FAILURE) {
19268                    writeRuntimePermissions = true;
19269                }
19270            // If permission review is enabled the permissions for a legacy apps
19271            // are represented as constantly granted runtime ones, so don't revoke.
19272            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19273                // Otherwise, reset the permission.
19274                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19275                switch (revokeResult) {
19276                    case PERMISSION_OPERATION_SUCCESS:
19277                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19278                        writeRuntimePermissions = true;
19279                        final int appId = ps.appId;
19280                        mHandler.post(new Runnable() {
19281                            @Override
19282                            public void run() {
19283                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19284                            }
19285                        });
19286                    } break;
19287                }
19288            }
19289        }
19290
19291        // Synchronously write as we are taking permissions away.
19292        if (writeRuntimePermissions) {
19293            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19294        }
19295
19296        // Synchronously write as we are taking permissions away.
19297        if (writeInstallPermissions) {
19298            mSettings.writeLPr();
19299        }
19300    }
19301
19302    /**
19303     * Remove entries from the keystore daemon. Will only remove it if the
19304     * {@code appId} is valid.
19305     */
19306    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19307        if (appId < 0) {
19308            return;
19309        }
19310
19311        final KeyStore keyStore = KeyStore.getInstance();
19312        if (keyStore != null) {
19313            if (userId == UserHandle.USER_ALL) {
19314                for (final int individual : sUserManager.getUserIds()) {
19315                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19316                }
19317            } else {
19318                keyStore.clearUid(UserHandle.getUid(userId, appId));
19319            }
19320        } else {
19321            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19322        }
19323    }
19324
19325    @Override
19326    public void deleteApplicationCacheFiles(final String packageName,
19327            final IPackageDataObserver observer) {
19328        final int userId = UserHandle.getCallingUserId();
19329        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19330    }
19331
19332    @Override
19333    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19334            final IPackageDataObserver observer) {
19335        final int callingUid = Binder.getCallingUid();
19336        if (mContext.checkCallingOrSelfPermission(
19337                android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES)
19338                != PackageManager.PERMISSION_GRANTED) {
19339            // If the caller has the old delete cache permission, silently ignore.  Else throw.
19340            if (mContext.checkCallingOrSelfPermission(
19341                    android.Manifest.permission.DELETE_CACHE_FILES)
19342                    == PackageManager.PERMISSION_GRANTED) {
19343                Slog.w(TAG, "Calling uid " + callingUid + " does not have " +
19344                        android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES +
19345                        ", silently ignoring");
19346                return;
19347            }
19348            mContext.enforceCallingOrSelfPermission(
19349                    android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES, null);
19350        }
19351        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19352                /* requireFullPermission= */ true, /* checkShell= */ false,
19353                "delete application cache files");
19354        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
19355                android.Manifest.permission.ACCESS_INSTANT_APPS);
19356
19357        final PackageParser.Package pkg;
19358        synchronized (mPackages) {
19359            pkg = mPackages.get(packageName);
19360        }
19361
19362        // Queue up an async operation since the package deletion may take a little while.
19363        mHandler.post(new Runnable() {
19364            public void run() {
19365                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
19366                boolean doClearData = true;
19367                if (ps != null) {
19368                    final boolean targetIsInstantApp =
19369                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19370                    doClearData = !targetIsInstantApp
19371                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
19372                }
19373                if (doClearData) {
19374                    synchronized (mInstallLock) {
19375                        final int flags = StorageManager.FLAG_STORAGE_DE
19376                                | StorageManager.FLAG_STORAGE_CE;
19377                        // We're only clearing cache files, so we don't care if the
19378                        // app is unfrozen and still able to run
19379                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19380                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19381                    }
19382                    clearExternalStorageDataSync(packageName, userId, false);
19383                }
19384                if (observer != null) {
19385                    try {
19386                        observer.onRemoveCompleted(packageName, true);
19387                    } catch (RemoteException e) {
19388                        Log.i(TAG, "Observer no longer exists.");
19389                    }
19390                }
19391            }
19392        });
19393    }
19394
19395    @Override
19396    public void getPackageSizeInfo(final String packageName, int userHandle,
19397            final IPackageStatsObserver observer) {
19398        throw new UnsupportedOperationException(
19399                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19400    }
19401
19402    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19403        final PackageSetting ps;
19404        synchronized (mPackages) {
19405            ps = mSettings.mPackages.get(packageName);
19406            if (ps == null) {
19407                Slog.w(TAG, "Failed to find settings for " + packageName);
19408                return false;
19409            }
19410        }
19411
19412        final String[] packageNames = { packageName };
19413        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19414        final String[] codePaths = { ps.codePathString };
19415
19416        try {
19417            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19418                    ps.appId, ceDataInodes, codePaths, stats);
19419
19420            // For now, ignore code size of packages on system partition
19421            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19422                stats.codeSize = 0;
19423            }
19424
19425            // External clients expect these to be tracked separately
19426            stats.dataSize -= stats.cacheSize;
19427
19428        } catch (InstallerException e) {
19429            Slog.w(TAG, String.valueOf(e));
19430            return false;
19431        }
19432
19433        return true;
19434    }
19435
19436    private int getUidTargetSdkVersionLockedLPr(int uid) {
19437        Object obj = mSettings.getUserIdLPr(uid);
19438        if (obj instanceof SharedUserSetting) {
19439            final SharedUserSetting sus = (SharedUserSetting) obj;
19440            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19441            final Iterator<PackageSetting> it = sus.packages.iterator();
19442            while (it.hasNext()) {
19443                final PackageSetting ps = it.next();
19444                if (ps.pkg != null) {
19445                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19446                    if (v < vers) vers = v;
19447                }
19448            }
19449            return vers;
19450        } else if (obj instanceof PackageSetting) {
19451            final PackageSetting ps = (PackageSetting) obj;
19452            if (ps.pkg != null) {
19453                return ps.pkg.applicationInfo.targetSdkVersion;
19454            }
19455        }
19456        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19457    }
19458
19459    private int getPackageTargetSdkVersionLockedLPr(String packageName) {
19460        final PackageParser.Package p = mPackages.get(packageName);
19461        if (p != null) {
19462            return p.applicationInfo.targetSdkVersion;
19463        }
19464        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19465    }
19466
19467    @Override
19468    public void addPreferredActivity(IntentFilter filter, int match,
19469            ComponentName[] set, ComponentName activity, int userId) {
19470        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19471                "Adding preferred");
19472    }
19473
19474    private void addPreferredActivityInternal(IntentFilter filter, int match,
19475            ComponentName[] set, ComponentName activity, boolean always, int userId,
19476            String opname) {
19477        // writer
19478        int callingUid = Binder.getCallingUid();
19479        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19480                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19481        if (filter.countActions() == 0) {
19482            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19483            return;
19484        }
19485        synchronized (mPackages) {
19486            if (mContext.checkCallingOrSelfPermission(
19487                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19488                    != PackageManager.PERMISSION_GRANTED) {
19489                if (getUidTargetSdkVersionLockedLPr(callingUid)
19490                        < Build.VERSION_CODES.FROYO) {
19491                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19492                            + callingUid);
19493                    return;
19494                }
19495                mContext.enforceCallingOrSelfPermission(
19496                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19497            }
19498
19499            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19500            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19501                    + userId + ":");
19502            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19503            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19504            scheduleWritePackageRestrictionsLocked(userId);
19505            postPreferredActivityChangedBroadcast(userId);
19506        }
19507    }
19508
19509    private void postPreferredActivityChangedBroadcast(int userId) {
19510        mHandler.post(() -> {
19511            final IActivityManager am = ActivityManager.getService();
19512            if (am == null) {
19513                return;
19514            }
19515
19516            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19517            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19518            try {
19519                am.broadcastIntent(null, intent, null, null,
19520                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19521                        null, false, false, userId);
19522            } catch (RemoteException e) {
19523            }
19524        });
19525    }
19526
19527    @Override
19528    public void replacePreferredActivity(IntentFilter filter, int match,
19529            ComponentName[] set, ComponentName activity, int userId) {
19530        if (filter.countActions() != 1) {
19531            throw new IllegalArgumentException(
19532                    "replacePreferredActivity expects filter to have only 1 action.");
19533        }
19534        if (filter.countDataAuthorities() != 0
19535                || filter.countDataPaths() != 0
19536                || filter.countDataSchemes() > 1
19537                || filter.countDataTypes() != 0) {
19538            throw new IllegalArgumentException(
19539                    "replacePreferredActivity expects filter to have no data authorities, " +
19540                    "paths, or types; and at most one scheme.");
19541        }
19542
19543        final int callingUid = Binder.getCallingUid();
19544        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19545                true /* requireFullPermission */, false /* checkShell */,
19546                "replace preferred activity");
19547        synchronized (mPackages) {
19548            if (mContext.checkCallingOrSelfPermission(
19549                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19550                    != PackageManager.PERMISSION_GRANTED) {
19551                if (getUidTargetSdkVersionLockedLPr(callingUid)
19552                        < Build.VERSION_CODES.FROYO) {
19553                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19554                            + Binder.getCallingUid());
19555                    return;
19556                }
19557                mContext.enforceCallingOrSelfPermission(
19558                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19559            }
19560
19561            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19562            if (pir != null) {
19563                // Get all of the existing entries that exactly match this filter.
19564                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19565                if (existing != null && existing.size() == 1) {
19566                    PreferredActivity cur = existing.get(0);
19567                    if (DEBUG_PREFERRED) {
19568                        Slog.i(TAG, "Checking replace of preferred:");
19569                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19570                        if (!cur.mPref.mAlways) {
19571                            Slog.i(TAG, "  -- CUR; not mAlways!");
19572                        } else {
19573                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19574                            Slog.i(TAG, "  -- CUR: mSet="
19575                                    + Arrays.toString(cur.mPref.mSetComponents));
19576                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19577                            Slog.i(TAG, "  -- NEW: mMatch="
19578                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19579                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19580                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19581                        }
19582                    }
19583                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19584                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19585                            && cur.mPref.sameSet(set)) {
19586                        // Setting the preferred activity to what it happens to be already
19587                        if (DEBUG_PREFERRED) {
19588                            Slog.i(TAG, "Replacing with same preferred activity "
19589                                    + cur.mPref.mShortComponent + " for user "
19590                                    + userId + ":");
19591                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19592                        }
19593                        return;
19594                    }
19595                }
19596
19597                if (existing != null) {
19598                    if (DEBUG_PREFERRED) {
19599                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19600                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19601                    }
19602                    for (int i = 0; i < existing.size(); i++) {
19603                        PreferredActivity pa = existing.get(i);
19604                        if (DEBUG_PREFERRED) {
19605                            Slog.i(TAG, "Removing existing preferred activity "
19606                                    + pa.mPref.mComponent + ":");
19607                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19608                        }
19609                        pir.removeFilter(pa);
19610                    }
19611                }
19612            }
19613            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19614                    "Replacing preferred");
19615        }
19616    }
19617
19618    @Override
19619    public void clearPackagePreferredActivities(String packageName) {
19620        final int callingUid = Binder.getCallingUid();
19621        if (getInstantAppPackageName(callingUid) != null) {
19622            return;
19623        }
19624        // writer
19625        synchronized (mPackages) {
19626            PackageParser.Package pkg = mPackages.get(packageName);
19627            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
19628                if (mContext.checkCallingOrSelfPermission(
19629                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19630                        != PackageManager.PERMISSION_GRANTED) {
19631                    if (getUidTargetSdkVersionLockedLPr(callingUid)
19632                            < Build.VERSION_CODES.FROYO) {
19633                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19634                                + callingUid);
19635                        return;
19636                    }
19637                    mContext.enforceCallingOrSelfPermission(
19638                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19639                }
19640            }
19641            final PackageSetting ps = mSettings.getPackageLPr(packageName);
19642            if (ps != null
19643                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
19644                return;
19645            }
19646            int user = UserHandle.getCallingUserId();
19647            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19648                scheduleWritePackageRestrictionsLocked(user);
19649            }
19650        }
19651    }
19652
19653    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19654    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19655        ArrayList<PreferredActivity> removed = null;
19656        boolean changed = false;
19657        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19658            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19659            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19660            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19661                continue;
19662            }
19663            Iterator<PreferredActivity> it = pir.filterIterator();
19664            while (it.hasNext()) {
19665                PreferredActivity pa = it.next();
19666                // Mark entry for removal only if it matches the package name
19667                // and the entry is of type "always".
19668                if (packageName == null ||
19669                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19670                                && pa.mPref.mAlways)) {
19671                    if (removed == null) {
19672                        removed = new ArrayList<PreferredActivity>();
19673                    }
19674                    removed.add(pa);
19675                }
19676            }
19677            if (removed != null) {
19678                for (int j=0; j<removed.size(); j++) {
19679                    PreferredActivity pa = removed.get(j);
19680                    pir.removeFilter(pa);
19681                }
19682                changed = true;
19683            }
19684        }
19685        if (changed) {
19686            postPreferredActivityChangedBroadcast(userId);
19687        }
19688        return changed;
19689    }
19690
19691    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19692    private void clearIntentFilterVerificationsLPw(int userId) {
19693        final int packageCount = mPackages.size();
19694        for (int i = 0; i < packageCount; i++) {
19695            PackageParser.Package pkg = mPackages.valueAt(i);
19696            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19697        }
19698    }
19699
19700    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19701    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19702        if (userId == UserHandle.USER_ALL) {
19703            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19704                    sUserManager.getUserIds())) {
19705                for (int oneUserId : sUserManager.getUserIds()) {
19706                    scheduleWritePackageRestrictionsLocked(oneUserId);
19707                }
19708            }
19709        } else {
19710            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19711                scheduleWritePackageRestrictionsLocked(userId);
19712            }
19713        }
19714    }
19715
19716    /** Clears state for all users, and touches intent filter verification policy */
19717    void clearDefaultBrowserIfNeeded(String packageName) {
19718        for (int oneUserId : sUserManager.getUserIds()) {
19719            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19720        }
19721    }
19722
19723    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19724        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19725        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19726            if (packageName.equals(defaultBrowserPackageName)) {
19727                setDefaultBrowserPackageName(null, userId);
19728            }
19729        }
19730    }
19731
19732    @Override
19733    public void resetApplicationPreferences(int userId) {
19734        mContext.enforceCallingOrSelfPermission(
19735                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19736        final long identity = Binder.clearCallingIdentity();
19737        // writer
19738        try {
19739            synchronized (mPackages) {
19740                clearPackagePreferredActivitiesLPw(null, userId);
19741                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19742                // TODO: We have to reset the default SMS and Phone. This requires
19743                // significant refactoring to keep all default apps in the package
19744                // manager (cleaner but more work) or have the services provide
19745                // callbacks to the package manager to request a default app reset.
19746                applyFactoryDefaultBrowserLPw(userId);
19747                clearIntentFilterVerificationsLPw(userId);
19748                primeDomainVerificationsLPw(userId);
19749                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19750                scheduleWritePackageRestrictionsLocked(userId);
19751            }
19752            resetNetworkPolicies(userId);
19753        } finally {
19754            Binder.restoreCallingIdentity(identity);
19755        }
19756    }
19757
19758    @Override
19759    public int getPreferredActivities(List<IntentFilter> outFilters,
19760            List<ComponentName> outActivities, String packageName) {
19761        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19762            return 0;
19763        }
19764        int num = 0;
19765        final int userId = UserHandle.getCallingUserId();
19766        // reader
19767        synchronized (mPackages) {
19768            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19769            if (pir != null) {
19770                final Iterator<PreferredActivity> it = pir.filterIterator();
19771                while (it.hasNext()) {
19772                    final PreferredActivity pa = it.next();
19773                    if (packageName == null
19774                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19775                                    && pa.mPref.mAlways)) {
19776                        if (outFilters != null) {
19777                            outFilters.add(new IntentFilter(pa));
19778                        }
19779                        if (outActivities != null) {
19780                            outActivities.add(pa.mPref.mComponent);
19781                        }
19782                    }
19783                }
19784            }
19785        }
19786
19787        return num;
19788    }
19789
19790    @Override
19791    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19792            int userId) {
19793        int callingUid = Binder.getCallingUid();
19794        if (callingUid != Process.SYSTEM_UID) {
19795            throw new SecurityException(
19796                    "addPersistentPreferredActivity can only be run by the system");
19797        }
19798        if (filter.countActions() == 0) {
19799            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19800            return;
19801        }
19802        synchronized (mPackages) {
19803            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19804                    ":");
19805            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19806            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19807                    new PersistentPreferredActivity(filter, activity));
19808            scheduleWritePackageRestrictionsLocked(userId);
19809            postPreferredActivityChangedBroadcast(userId);
19810        }
19811    }
19812
19813    @Override
19814    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19815        int callingUid = Binder.getCallingUid();
19816        if (callingUid != Process.SYSTEM_UID) {
19817            throw new SecurityException(
19818                    "clearPackagePersistentPreferredActivities can only be run by the system");
19819        }
19820        ArrayList<PersistentPreferredActivity> removed = null;
19821        boolean changed = false;
19822        synchronized (mPackages) {
19823            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19824                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19825                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19826                        .valueAt(i);
19827                if (userId != thisUserId) {
19828                    continue;
19829                }
19830                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19831                while (it.hasNext()) {
19832                    PersistentPreferredActivity ppa = it.next();
19833                    // Mark entry for removal only if it matches the package name.
19834                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19835                        if (removed == null) {
19836                            removed = new ArrayList<PersistentPreferredActivity>();
19837                        }
19838                        removed.add(ppa);
19839                    }
19840                }
19841                if (removed != null) {
19842                    for (int j=0; j<removed.size(); j++) {
19843                        PersistentPreferredActivity ppa = removed.get(j);
19844                        ppir.removeFilter(ppa);
19845                    }
19846                    changed = true;
19847                }
19848            }
19849
19850            if (changed) {
19851                scheduleWritePackageRestrictionsLocked(userId);
19852                postPreferredActivityChangedBroadcast(userId);
19853            }
19854        }
19855    }
19856
19857    /**
19858     * Common machinery for picking apart a restored XML blob and passing
19859     * it to a caller-supplied functor to be applied to the running system.
19860     */
19861    private void restoreFromXml(XmlPullParser parser, int userId,
19862            String expectedStartTag, BlobXmlRestorer functor)
19863            throws IOException, XmlPullParserException {
19864        int type;
19865        while ((type = parser.next()) != XmlPullParser.START_TAG
19866                && type != XmlPullParser.END_DOCUMENT) {
19867        }
19868        if (type != XmlPullParser.START_TAG) {
19869            // oops didn't find a start tag?!
19870            if (DEBUG_BACKUP) {
19871                Slog.e(TAG, "Didn't find start tag during restore");
19872            }
19873            return;
19874        }
19875Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19876        // this is supposed to be TAG_PREFERRED_BACKUP
19877        if (!expectedStartTag.equals(parser.getName())) {
19878            if (DEBUG_BACKUP) {
19879                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19880            }
19881            return;
19882        }
19883
19884        // skip interfering stuff, then we're aligned with the backing implementation
19885        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19886Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19887        functor.apply(parser, userId);
19888    }
19889
19890    private interface BlobXmlRestorer {
19891        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19892    }
19893
19894    /**
19895     * Non-Binder method, support for the backup/restore mechanism: write the
19896     * full set of preferred activities in its canonical XML format.  Returns the
19897     * XML output as a byte array, or null if there is none.
19898     */
19899    @Override
19900    public byte[] getPreferredActivityBackup(int userId) {
19901        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19902            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19903        }
19904
19905        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19906        try {
19907            final XmlSerializer serializer = new FastXmlSerializer();
19908            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19909            serializer.startDocument(null, true);
19910            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19911
19912            synchronized (mPackages) {
19913                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19914            }
19915
19916            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19917            serializer.endDocument();
19918            serializer.flush();
19919        } catch (Exception e) {
19920            if (DEBUG_BACKUP) {
19921                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19922            }
19923            return null;
19924        }
19925
19926        return dataStream.toByteArray();
19927    }
19928
19929    @Override
19930    public void restorePreferredActivities(byte[] backup, int userId) {
19931        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19932            throw new SecurityException("Only the system may call restorePreferredActivities()");
19933        }
19934
19935        try {
19936            final XmlPullParser parser = Xml.newPullParser();
19937            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19938            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19939                    new BlobXmlRestorer() {
19940                        @Override
19941                        public void apply(XmlPullParser parser, int userId)
19942                                throws XmlPullParserException, IOException {
19943                            synchronized (mPackages) {
19944                                mSettings.readPreferredActivitiesLPw(parser, userId);
19945                            }
19946                        }
19947                    } );
19948        } catch (Exception e) {
19949            if (DEBUG_BACKUP) {
19950                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19951            }
19952        }
19953    }
19954
19955    /**
19956     * Non-Binder method, support for the backup/restore mechanism: write the
19957     * default browser (etc) settings in its canonical XML format.  Returns the default
19958     * browser XML representation as a byte array, or null if there is none.
19959     */
19960    @Override
19961    public byte[] getDefaultAppsBackup(int userId) {
19962        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19963            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19964        }
19965
19966        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19967        try {
19968            final XmlSerializer serializer = new FastXmlSerializer();
19969            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19970            serializer.startDocument(null, true);
19971            serializer.startTag(null, TAG_DEFAULT_APPS);
19972
19973            synchronized (mPackages) {
19974                mSettings.writeDefaultAppsLPr(serializer, userId);
19975            }
19976
19977            serializer.endTag(null, TAG_DEFAULT_APPS);
19978            serializer.endDocument();
19979            serializer.flush();
19980        } catch (Exception e) {
19981            if (DEBUG_BACKUP) {
19982                Slog.e(TAG, "Unable to write default apps for backup", e);
19983            }
19984            return null;
19985        }
19986
19987        return dataStream.toByteArray();
19988    }
19989
19990    @Override
19991    public void restoreDefaultApps(byte[] backup, int userId) {
19992        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19993            throw new SecurityException("Only the system may call restoreDefaultApps()");
19994        }
19995
19996        try {
19997            final XmlPullParser parser = Xml.newPullParser();
19998            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19999            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20000                    new BlobXmlRestorer() {
20001                        @Override
20002                        public void apply(XmlPullParser parser, int userId)
20003                                throws XmlPullParserException, IOException {
20004                            synchronized (mPackages) {
20005                                mSettings.readDefaultAppsLPw(parser, userId);
20006                            }
20007                        }
20008                    } );
20009        } catch (Exception e) {
20010            if (DEBUG_BACKUP) {
20011                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20012            }
20013        }
20014    }
20015
20016    @Override
20017    public byte[] getIntentFilterVerificationBackup(int userId) {
20018        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20019            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20020        }
20021
20022        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20023        try {
20024            final XmlSerializer serializer = new FastXmlSerializer();
20025            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20026            serializer.startDocument(null, true);
20027            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20028
20029            synchronized (mPackages) {
20030                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20031            }
20032
20033            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20034            serializer.endDocument();
20035            serializer.flush();
20036        } catch (Exception e) {
20037            if (DEBUG_BACKUP) {
20038                Slog.e(TAG, "Unable to write default apps for backup", e);
20039            }
20040            return null;
20041        }
20042
20043        return dataStream.toByteArray();
20044    }
20045
20046    @Override
20047    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20048        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20049            throw new SecurityException("Only the system may call restorePreferredActivities()");
20050        }
20051
20052        try {
20053            final XmlPullParser parser = Xml.newPullParser();
20054            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20055            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20056                    new BlobXmlRestorer() {
20057                        @Override
20058                        public void apply(XmlPullParser parser, int userId)
20059                                throws XmlPullParserException, IOException {
20060                            synchronized (mPackages) {
20061                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20062                                mSettings.writeLPr();
20063                            }
20064                        }
20065                    } );
20066        } catch (Exception e) {
20067            if (DEBUG_BACKUP) {
20068                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20069            }
20070        }
20071    }
20072
20073    @Override
20074    public byte[] getPermissionGrantBackup(int userId) {
20075        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20076            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20077        }
20078
20079        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20080        try {
20081            final XmlSerializer serializer = new FastXmlSerializer();
20082            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20083            serializer.startDocument(null, true);
20084            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20085
20086            synchronized (mPackages) {
20087                serializeRuntimePermissionGrantsLPr(serializer, userId);
20088            }
20089
20090            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20091            serializer.endDocument();
20092            serializer.flush();
20093        } catch (Exception e) {
20094            if (DEBUG_BACKUP) {
20095                Slog.e(TAG, "Unable to write default apps for backup", e);
20096            }
20097            return null;
20098        }
20099
20100        return dataStream.toByteArray();
20101    }
20102
20103    @Override
20104    public void restorePermissionGrants(byte[] backup, int userId) {
20105        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20106            throw new SecurityException("Only the system may call restorePermissionGrants()");
20107        }
20108
20109        try {
20110            final XmlPullParser parser = Xml.newPullParser();
20111            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20112            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20113                    new BlobXmlRestorer() {
20114                        @Override
20115                        public void apply(XmlPullParser parser, int userId)
20116                                throws XmlPullParserException, IOException {
20117                            synchronized (mPackages) {
20118                                processRestoredPermissionGrantsLPr(parser, userId);
20119                            }
20120                        }
20121                    } );
20122        } catch (Exception e) {
20123            if (DEBUG_BACKUP) {
20124                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20125            }
20126        }
20127    }
20128
20129    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20130            throws IOException {
20131        serializer.startTag(null, TAG_ALL_GRANTS);
20132
20133        final int N = mSettings.mPackages.size();
20134        for (int i = 0; i < N; i++) {
20135            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20136            boolean pkgGrantsKnown = false;
20137
20138            PermissionsState packagePerms = ps.getPermissionsState();
20139
20140            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20141                final int grantFlags = state.getFlags();
20142                // only look at grants that are not system/policy fixed
20143                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20144                    final boolean isGranted = state.isGranted();
20145                    // And only back up the user-twiddled state bits
20146                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20147                        final String packageName = mSettings.mPackages.keyAt(i);
20148                        if (!pkgGrantsKnown) {
20149                            serializer.startTag(null, TAG_GRANT);
20150                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20151                            pkgGrantsKnown = true;
20152                        }
20153
20154                        final boolean userSet =
20155                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20156                        final boolean userFixed =
20157                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20158                        final boolean revoke =
20159                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20160
20161                        serializer.startTag(null, TAG_PERMISSION);
20162                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20163                        if (isGranted) {
20164                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20165                        }
20166                        if (userSet) {
20167                            serializer.attribute(null, ATTR_USER_SET, "true");
20168                        }
20169                        if (userFixed) {
20170                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20171                        }
20172                        if (revoke) {
20173                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20174                        }
20175                        serializer.endTag(null, TAG_PERMISSION);
20176                    }
20177                }
20178            }
20179
20180            if (pkgGrantsKnown) {
20181                serializer.endTag(null, TAG_GRANT);
20182            }
20183        }
20184
20185        serializer.endTag(null, TAG_ALL_GRANTS);
20186    }
20187
20188    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20189            throws XmlPullParserException, IOException {
20190        String pkgName = null;
20191        int outerDepth = parser.getDepth();
20192        int type;
20193        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20194                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20195            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20196                continue;
20197            }
20198
20199            final String tagName = parser.getName();
20200            if (tagName.equals(TAG_GRANT)) {
20201                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20202                if (DEBUG_BACKUP) {
20203                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20204                }
20205            } else if (tagName.equals(TAG_PERMISSION)) {
20206
20207                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20208                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20209
20210                int newFlagSet = 0;
20211                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20212                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20213                }
20214                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20215                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20216                }
20217                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20218                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20219                }
20220                if (DEBUG_BACKUP) {
20221                    Slog.v(TAG, "  + Restoring grant:"
20222                            + " pkg=" + pkgName
20223                            + " perm=" + permName
20224                            + " granted=" + isGranted
20225                            + " bits=0x" + Integer.toHexString(newFlagSet));
20226                }
20227                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20228                if (ps != null) {
20229                    // Already installed so we apply the grant immediately
20230                    if (DEBUG_BACKUP) {
20231                        Slog.v(TAG, "        + already installed; applying");
20232                    }
20233                    PermissionsState perms = ps.getPermissionsState();
20234                    BasePermission bp =
20235                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
20236                    if (bp != null) {
20237                        if (isGranted) {
20238                            perms.grantRuntimePermission(bp, userId);
20239                        }
20240                        if (newFlagSet != 0) {
20241                            perms.updatePermissionFlags(
20242                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20243                        }
20244                    }
20245                } else {
20246                    // Need to wait for post-restore install to apply the grant
20247                    if (DEBUG_BACKUP) {
20248                        Slog.v(TAG, "        - not yet installed; saving for later");
20249                    }
20250                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20251                            isGranted, newFlagSet, userId);
20252                }
20253            } else {
20254                PackageManagerService.reportSettingsProblem(Log.WARN,
20255                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20256                XmlUtils.skipCurrentTag(parser);
20257            }
20258        }
20259
20260        scheduleWriteSettingsLocked();
20261        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20262    }
20263
20264    @Override
20265    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20266            int sourceUserId, int targetUserId, int flags) {
20267        mContext.enforceCallingOrSelfPermission(
20268                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20269        int callingUid = Binder.getCallingUid();
20270        enforceOwnerRights(ownerPackage, callingUid);
20271        PackageManagerServiceUtils.enforceShellRestriction(
20272                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20273        if (intentFilter.countActions() == 0) {
20274            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20275            return;
20276        }
20277        synchronized (mPackages) {
20278            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20279                    ownerPackage, targetUserId, flags);
20280            CrossProfileIntentResolver resolver =
20281                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20282            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20283            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20284            if (existing != null) {
20285                int size = existing.size();
20286                for (int i = 0; i < size; i++) {
20287                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20288                        return;
20289                    }
20290                }
20291            }
20292            resolver.addFilter(newFilter);
20293            scheduleWritePackageRestrictionsLocked(sourceUserId);
20294        }
20295    }
20296
20297    @Override
20298    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20299        mContext.enforceCallingOrSelfPermission(
20300                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20301        final int callingUid = Binder.getCallingUid();
20302        enforceOwnerRights(ownerPackage, callingUid);
20303        PackageManagerServiceUtils.enforceShellRestriction(
20304                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20305        synchronized (mPackages) {
20306            CrossProfileIntentResolver resolver =
20307                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20308            ArraySet<CrossProfileIntentFilter> set =
20309                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20310            for (CrossProfileIntentFilter filter : set) {
20311                if (filter.getOwnerPackage().equals(ownerPackage)) {
20312                    resolver.removeFilter(filter);
20313                }
20314            }
20315            scheduleWritePackageRestrictionsLocked(sourceUserId);
20316        }
20317    }
20318
20319    // Enforcing that callingUid is owning pkg on userId
20320    private void enforceOwnerRights(String pkg, int callingUid) {
20321        // The system owns everything.
20322        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20323            return;
20324        }
20325        final int callingUserId = UserHandle.getUserId(callingUid);
20326        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20327        if (pi == null) {
20328            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20329                    + callingUserId);
20330        }
20331        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20332            throw new SecurityException("Calling uid " + callingUid
20333                    + " does not own package " + pkg);
20334        }
20335    }
20336
20337    @Override
20338    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20339        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20340            return null;
20341        }
20342        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20343    }
20344
20345    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20346        UserManagerService ums = UserManagerService.getInstance();
20347        if (ums != null) {
20348            final UserInfo parent = ums.getProfileParent(userId);
20349            final int launcherUid = (parent != null) ? parent.id : userId;
20350            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20351            if (launcherComponent != null) {
20352                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20353                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20354                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20355                        .setPackage(launcherComponent.getPackageName());
20356                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20357            }
20358        }
20359    }
20360
20361    /**
20362     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20363     * then reports the most likely home activity or null if there are more than one.
20364     */
20365    private ComponentName getDefaultHomeActivity(int userId) {
20366        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20367        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20368        if (cn != null) {
20369            return cn;
20370        }
20371
20372        // Find the launcher with the highest priority and return that component if there are no
20373        // other home activity with the same priority.
20374        int lastPriority = Integer.MIN_VALUE;
20375        ComponentName lastComponent = null;
20376        final int size = allHomeCandidates.size();
20377        for (int i = 0; i < size; i++) {
20378            final ResolveInfo ri = allHomeCandidates.get(i);
20379            if (ri.priority > lastPriority) {
20380                lastComponent = ri.activityInfo.getComponentName();
20381                lastPriority = ri.priority;
20382            } else if (ri.priority == lastPriority) {
20383                // Two components found with same priority.
20384                lastComponent = null;
20385            }
20386        }
20387        return lastComponent;
20388    }
20389
20390    private Intent getHomeIntent() {
20391        Intent intent = new Intent(Intent.ACTION_MAIN);
20392        intent.addCategory(Intent.CATEGORY_HOME);
20393        intent.addCategory(Intent.CATEGORY_DEFAULT);
20394        return intent;
20395    }
20396
20397    private IntentFilter getHomeFilter() {
20398        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20399        filter.addCategory(Intent.CATEGORY_HOME);
20400        filter.addCategory(Intent.CATEGORY_DEFAULT);
20401        return filter;
20402    }
20403
20404    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20405            int userId) {
20406        Intent intent  = getHomeIntent();
20407        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20408                PackageManager.GET_META_DATA, userId);
20409        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20410                true, false, false, userId);
20411
20412        allHomeCandidates.clear();
20413        if (list != null) {
20414            for (ResolveInfo ri : list) {
20415                allHomeCandidates.add(ri);
20416            }
20417        }
20418        return (preferred == null || preferred.activityInfo == null)
20419                ? null
20420                : new ComponentName(preferred.activityInfo.packageName,
20421                        preferred.activityInfo.name);
20422    }
20423
20424    @Override
20425    public void setHomeActivity(ComponentName comp, int userId) {
20426        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20427            return;
20428        }
20429        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20430        getHomeActivitiesAsUser(homeActivities, userId);
20431
20432        boolean found = false;
20433
20434        final int size = homeActivities.size();
20435        final ComponentName[] set = new ComponentName[size];
20436        for (int i = 0; i < size; i++) {
20437            final ResolveInfo candidate = homeActivities.get(i);
20438            final ActivityInfo info = candidate.activityInfo;
20439            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20440            set[i] = activityName;
20441            if (!found && activityName.equals(comp)) {
20442                found = true;
20443            }
20444        }
20445        if (!found) {
20446            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20447                    + userId);
20448        }
20449        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20450                set, comp, userId);
20451    }
20452
20453    private @Nullable String getSetupWizardPackageName() {
20454        final Intent intent = new Intent(Intent.ACTION_MAIN);
20455        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20456
20457        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20458                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20459                        | MATCH_DISABLED_COMPONENTS,
20460                UserHandle.myUserId());
20461        if (matches.size() == 1) {
20462            return matches.get(0).getComponentInfo().packageName;
20463        } else {
20464            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20465                    + ": matches=" + matches);
20466            return null;
20467        }
20468    }
20469
20470    private @Nullable String getStorageManagerPackageName() {
20471        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20472
20473        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20474                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20475                        | MATCH_DISABLED_COMPONENTS,
20476                UserHandle.myUserId());
20477        if (matches.size() == 1) {
20478            return matches.get(0).getComponentInfo().packageName;
20479        } else {
20480            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20481                    + matches.size() + ": matches=" + matches);
20482            return null;
20483        }
20484    }
20485
20486    @Override
20487    public String getSystemTextClassifierPackageName() {
20488        return mContext.getString(R.string.config_defaultTextClassifierPackage);
20489    }
20490
20491    @Override
20492    public void setApplicationEnabledSetting(String appPackageName,
20493            int newState, int flags, int userId, String callingPackage) {
20494        if (!sUserManager.exists(userId)) return;
20495        if (callingPackage == null) {
20496            callingPackage = Integer.toString(Binder.getCallingUid());
20497        }
20498        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20499    }
20500
20501    @Override
20502    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20503        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20504        synchronized (mPackages) {
20505            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20506            if (pkgSetting != null) {
20507                pkgSetting.setUpdateAvailable(updateAvailable);
20508            }
20509        }
20510    }
20511
20512    @Override
20513    public void setComponentEnabledSetting(ComponentName componentName,
20514            int newState, int flags, int userId) {
20515        if (!sUserManager.exists(userId)) return;
20516        setEnabledSetting(componentName.getPackageName(),
20517                componentName.getClassName(), newState, flags, userId, null);
20518    }
20519
20520    private void setEnabledSetting(final String packageName, String className, int newState,
20521            final int flags, int userId, String callingPackage) {
20522        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20523              || newState == COMPONENT_ENABLED_STATE_ENABLED
20524              || newState == COMPONENT_ENABLED_STATE_DISABLED
20525              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20526              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20527            throw new IllegalArgumentException("Invalid new component state: "
20528                    + newState);
20529        }
20530        PackageSetting pkgSetting;
20531        final int callingUid = Binder.getCallingUid();
20532        final int permission;
20533        if (callingUid == Process.SYSTEM_UID) {
20534            permission = PackageManager.PERMISSION_GRANTED;
20535        } else {
20536            permission = mContext.checkCallingOrSelfPermission(
20537                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20538        }
20539        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20540                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20541        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20542        boolean sendNow = false;
20543        boolean isApp = (className == null);
20544        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
20545        String componentName = isApp ? packageName : className;
20546        int packageUid = -1;
20547        ArrayList<String> components;
20548
20549        // reader
20550        synchronized (mPackages) {
20551            pkgSetting = mSettings.mPackages.get(packageName);
20552            if (pkgSetting == null) {
20553                if (!isCallerInstantApp) {
20554                    if (className == null) {
20555                        throw new IllegalArgumentException("Unknown package: " + packageName);
20556                    }
20557                    throw new IllegalArgumentException(
20558                            "Unknown component: " + packageName + "/" + className);
20559                } else {
20560                    // throw SecurityException to prevent leaking package information
20561                    throw new SecurityException(
20562                            "Attempt to change component state; "
20563                            + "pid=" + Binder.getCallingPid()
20564                            + ", uid=" + callingUid
20565                            + (className == null
20566                                    ? ", package=" + packageName
20567                                    : ", component=" + packageName + "/" + className));
20568                }
20569            }
20570        }
20571
20572        // Limit who can change which apps
20573        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
20574            // Don't allow apps that don't have permission to modify other apps
20575            if (!allowedByPermission
20576                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
20577                throw new SecurityException(
20578                        "Attempt to change component state; "
20579                        + "pid=" + Binder.getCallingPid()
20580                        + ", uid=" + callingUid
20581                        + (className == null
20582                                ? ", package=" + packageName
20583                                : ", component=" + packageName + "/" + className));
20584            }
20585            // Don't allow changing protected packages.
20586            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20587                throw new SecurityException("Cannot disable a protected package: " + packageName);
20588            }
20589        }
20590
20591        synchronized (mPackages) {
20592            if (callingUid == Process.SHELL_UID
20593                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20594                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20595                // unless it is a test package.
20596                int oldState = pkgSetting.getEnabled(userId);
20597                if (className == null
20598                        &&
20599                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20600                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20601                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20602                        &&
20603                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20604                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
20605                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20606                    // ok
20607                } else {
20608                    throw new SecurityException(
20609                            "Shell cannot change component state for " + packageName + "/"
20610                                    + className + " to " + newState);
20611                }
20612            }
20613        }
20614        if (className == null) {
20615            // We're dealing with an application/package level state change
20616            synchronized (mPackages) {
20617                if (pkgSetting.getEnabled(userId) == newState) {
20618                    // Nothing to do
20619                    return;
20620                }
20621            }
20622            // If we're enabling a system stub, there's a little more work to do.
20623            // Prior to enabling the package, we need to decompress the APK(s) to the
20624            // data partition and then replace the version on the system partition.
20625            final PackageParser.Package deletedPkg = pkgSetting.pkg;
20626            final boolean isSystemStub = deletedPkg.isStub
20627                    && deletedPkg.isSystem();
20628            if (isSystemStub
20629                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20630                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
20631                final File codePath = decompressPackage(deletedPkg);
20632                if (codePath == null) {
20633                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
20634                    return;
20635                }
20636                // TODO remove direct parsing of the package object during internal cleanup
20637                // of scan package
20638                // We need to call parse directly here for no other reason than we need
20639                // the new package in order to disable the old one [we use the information
20640                // for some internal optimization to optionally create a new package setting
20641                // object on replace]. However, we can't get the package from the scan
20642                // because the scan modifies live structures and we need to remove the
20643                // old [system] package from the system before a scan can be attempted.
20644                // Once scan is indempotent we can remove this parse and use the package
20645                // object we scanned, prior to adding it to package settings.
20646                final PackageParser pp = new PackageParser();
20647                pp.setSeparateProcesses(mSeparateProcesses);
20648                pp.setDisplayMetrics(mMetrics);
20649                pp.setCallback(mPackageParserCallback);
20650                final PackageParser.Package tmpPkg;
20651                try {
20652                    final @ParseFlags int parseFlags = mDefParseFlags
20653                            | PackageParser.PARSE_MUST_BE_APK
20654                            | PackageParser.PARSE_IS_SYSTEM_DIR;
20655                    tmpPkg = pp.parsePackage(codePath, parseFlags);
20656                } catch (PackageParserException e) {
20657                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
20658                    return;
20659                }
20660                synchronized (mInstallLock) {
20661                    // Disable the stub and remove any package entries
20662                    removePackageLI(deletedPkg, true);
20663                    synchronized (mPackages) {
20664                        disableSystemPackageLPw(deletedPkg, tmpPkg);
20665                    }
20666                    final PackageParser.Package pkg;
20667                    try (PackageFreezer freezer =
20668                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20669                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
20670                                | PackageParser.PARSE_ENFORCE_CODE;
20671                        pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
20672                                0 /*currentTime*/, null /*user*/);
20673                        prepareAppDataAfterInstallLIF(pkg);
20674                        synchronized (mPackages) {
20675                            try {
20676                                updateSharedLibrariesLPr(pkg, null);
20677                            } catch (PackageManagerException e) {
20678                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
20679                            }
20680                            mPermissionManager.updatePermissions(
20681                                    pkg.packageName, pkg, true, mPackages.values(),
20682                                    mPermissionCallback);
20683                            mSettings.writeLPr();
20684                        }
20685                    } catch (PackageManagerException e) {
20686                        // Whoops! Something went wrong; try to roll back to the stub
20687                        Slog.w(TAG, "Failed to install compressed system package:"
20688                                + pkgSetting.name, e);
20689                        // Remove the failed install
20690                        removeCodePathLI(codePath);
20691
20692                        // Install the system package
20693                        try (PackageFreezer freezer =
20694                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20695                            synchronized (mPackages) {
20696                                // NOTE: The system package always needs to be enabled; even
20697                                // if it's for a compressed stub. If we don't, installing the
20698                                // system package fails during scan [scanning checks the disabled
20699                                // packages]. We will reverse this later, after we've "installed"
20700                                // the stub.
20701                                // This leaves us in a fragile state; the stub should never be
20702                                // enabled, so, cross your fingers and hope nothing goes wrong
20703                                // until we can disable the package later.
20704                                enableSystemPackageLPw(deletedPkg);
20705                            }
20706                            installPackageFromSystemLIF(deletedPkg.codePath,
20707                                    false /*isPrivileged*/, null /*allUserHandles*/,
20708                                    null /*origUserHandles*/, null /*origPermissionsState*/,
20709                                    true /*writeSettings*/);
20710                        } catch (PackageManagerException pme) {
20711                            Slog.w(TAG, "Failed to restore system package:"
20712                                    + deletedPkg.packageName, pme);
20713                        } finally {
20714                            synchronized (mPackages) {
20715                                mSettings.disableSystemPackageLPw(
20716                                        deletedPkg.packageName, true /*replaced*/);
20717                                mSettings.writeLPr();
20718                            }
20719                        }
20720                        return;
20721                    }
20722                    clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
20723                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20724                    mDexManager.notifyPackageUpdated(pkg.packageName,
20725                            pkg.baseCodePath, pkg.splitCodePaths);
20726                }
20727            }
20728            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20729                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20730                // Don't care about who enables an app.
20731                callingPackage = null;
20732            }
20733            synchronized (mPackages) {
20734                pkgSetting.setEnabled(newState, userId, callingPackage);
20735            }
20736        } else {
20737            synchronized (mPackages) {
20738                // We're dealing with a component level state change
20739                // First, verify that this is a valid class name.
20740                PackageParser.Package pkg = pkgSetting.pkg;
20741                if (pkg == null || !pkg.hasComponentClassName(className)) {
20742                    if (pkg != null &&
20743                            pkg.applicationInfo.targetSdkVersion >=
20744                                    Build.VERSION_CODES.JELLY_BEAN) {
20745                        throw new IllegalArgumentException("Component class " + className
20746                                + " does not exist in " + packageName);
20747                    } else {
20748                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20749                                + className + " does not exist in " + packageName);
20750                    }
20751                }
20752                switch (newState) {
20753                    case COMPONENT_ENABLED_STATE_ENABLED:
20754                        if (!pkgSetting.enableComponentLPw(className, userId)) {
20755                            return;
20756                        }
20757                        break;
20758                    case COMPONENT_ENABLED_STATE_DISABLED:
20759                        if (!pkgSetting.disableComponentLPw(className, userId)) {
20760                            return;
20761                        }
20762                        break;
20763                    case COMPONENT_ENABLED_STATE_DEFAULT:
20764                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
20765                            return;
20766                        }
20767                        break;
20768                    default:
20769                        Slog.e(TAG, "Invalid new component state: " + newState);
20770                        return;
20771                }
20772            }
20773        }
20774        synchronized (mPackages) {
20775            scheduleWritePackageRestrictionsLocked(userId);
20776            updateSequenceNumberLP(pkgSetting, new int[] { userId });
20777            final long callingId = Binder.clearCallingIdentity();
20778            try {
20779                updateInstantAppInstallerLocked(packageName);
20780            } finally {
20781                Binder.restoreCallingIdentity(callingId);
20782            }
20783            components = mPendingBroadcasts.get(userId, packageName);
20784            final boolean newPackage = components == null;
20785            if (newPackage) {
20786                components = new ArrayList<String>();
20787            }
20788            if (!components.contains(componentName)) {
20789                components.add(componentName);
20790            }
20791            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20792                sendNow = true;
20793                // Purge entry from pending broadcast list if another one exists already
20794                // since we are sending one right away.
20795                mPendingBroadcasts.remove(userId, packageName);
20796            } else {
20797                if (newPackage) {
20798                    mPendingBroadcasts.put(userId, packageName, components);
20799                }
20800                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20801                    // Schedule a message
20802                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20803                }
20804            }
20805        }
20806
20807        long callingId = Binder.clearCallingIdentity();
20808        try {
20809            if (sendNow) {
20810                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20811                sendPackageChangedBroadcast(packageName,
20812                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20813            }
20814        } finally {
20815            Binder.restoreCallingIdentity(callingId);
20816        }
20817    }
20818
20819    @Override
20820    public void flushPackageRestrictionsAsUser(int userId) {
20821        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20822            return;
20823        }
20824        if (!sUserManager.exists(userId)) {
20825            return;
20826        }
20827        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20828                false /* checkShell */, "flushPackageRestrictions");
20829        synchronized (mPackages) {
20830            mSettings.writePackageRestrictionsLPr(userId);
20831            mDirtyUsers.remove(userId);
20832            if (mDirtyUsers.isEmpty()) {
20833                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20834            }
20835        }
20836    }
20837
20838    private void sendPackageChangedBroadcast(String packageName,
20839            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20840        if (DEBUG_INSTALL)
20841            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20842                    + componentNames);
20843        Bundle extras = new Bundle(4);
20844        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20845        String nameList[] = new String[componentNames.size()];
20846        componentNames.toArray(nameList);
20847        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20848        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20849        extras.putInt(Intent.EXTRA_UID, packageUid);
20850        // If this is not reporting a change of the overall package, then only send it
20851        // to registered receivers.  We don't want to launch a swath of apps for every
20852        // little component state change.
20853        final int flags = !componentNames.contains(packageName)
20854                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20855        final int userId = UserHandle.getUserId(packageUid);
20856        final boolean isInstantApp = isInstantApp(packageName, userId);
20857        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
20858        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
20859        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20860                userIds, instantUserIds);
20861    }
20862
20863    @Override
20864    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20865        if (!sUserManager.exists(userId)) return;
20866        final int callingUid = Binder.getCallingUid();
20867        if (getInstantAppPackageName(callingUid) != null) {
20868            return;
20869        }
20870        final int permission = mContext.checkCallingOrSelfPermission(
20871                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20872        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20873        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20874                true /* requireFullPermission */, true /* checkShell */, "stop package");
20875        // writer
20876        synchronized (mPackages) {
20877            final PackageSetting ps = mSettings.mPackages.get(packageName);
20878            if (!filterAppAccessLPr(ps, callingUid, userId)
20879                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20880                            allowedByPermission, callingUid, userId)) {
20881                scheduleWritePackageRestrictionsLocked(userId);
20882            }
20883        }
20884    }
20885
20886    @Override
20887    public String getInstallerPackageName(String packageName) {
20888        final int callingUid = Binder.getCallingUid();
20889        synchronized (mPackages) {
20890            final PackageSetting ps = mSettings.mPackages.get(packageName);
20891            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20892                return null;
20893            }
20894            return mSettings.getInstallerPackageNameLPr(packageName);
20895        }
20896    }
20897
20898    public boolean isOrphaned(String packageName) {
20899        // reader
20900        synchronized (mPackages) {
20901            return mSettings.isOrphaned(packageName);
20902        }
20903    }
20904
20905    @Override
20906    public int getApplicationEnabledSetting(String packageName, int userId) {
20907        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20908        int callingUid = Binder.getCallingUid();
20909        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20910                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20911        // reader
20912        synchronized (mPackages) {
20913            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
20914                return COMPONENT_ENABLED_STATE_DISABLED;
20915            }
20916            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20917        }
20918    }
20919
20920    @Override
20921    public int getComponentEnabledSetting(ComponentName component, int userId) {
20922        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20923        int callingUid = Binder.getCallingUid();
20924        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20925                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
20926        synchronized (mPackages) {
20927            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
20928                    component, TYPE_UNKNOWN, userId)) {
20929                return COMPONENT_ENABLED_STATE_DISABLED;
20930            }
20931            return mSettings.getComponentEnabledSettingLPr(component, userId);
20932        }
20933    }
20934
20935    @Override
20936    public void enterSafeMode() {
20937        enforceSystemOrRoot("Only the system can request entering safe mode");
20938
20939        if (!mSystemReady) {
20940            mSafeMode = true;
20941        }
20942    }
20943
20944    @Override
20945    public void systemReady() {
20946        enforceSystemOrRoot("Only the system can claim the system is ready");
20947
20948        mSystemReady = true;
20949        final ContentResolver resolver = mContext.getContentResolver();
20950        ContentObserver co = new ContentObserver(mHandler) {
20951            @Override
20952            public void onChange(boolean selfChange) {
20953                mWebInstantAppsDisabled =
20954                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20955                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20956            }
20957        };
20958        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20959                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20960                false, co, UserHandle.USER_SYSTEM);
20961        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Secure
20962                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20963        co.onChange(true);
20964
20965        // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to
20966        // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once
20967        // it is done.
20968        ContentObserver privAppOobObserver = new ContentObserver(mHandler) {
20969            @Override
20970            public void onChange(boolean selfChange) {
20971                int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0);
20972                SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB,
20973                        oobEnabled == 1 ? "true" : "false");
20974            }
20975        };
20976        mContext.getContentResolver().registerContentObserver(
20977                Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver,
20978                UserHandle.USER_SYSTEM);
20979        // At boot, restore the value from the setting, which persists across reboot.
20980        privAppOobObserver.onChange(true);
20981
20982        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20983        // disabled after already being started.
20984        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20985                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20986
20987        // Read the compatibilty setting when the system is ready.
20988        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20989                mContext.getContentResolver(),
20990                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20991        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20992        if (DEBUG_SETTINGS) {
20993            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20994        }
20995
20996        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20997
20998        synchronized (mPackages) {
20999            // Verify that all of the preferred activity components actually
21000            // exist.  It is possible for applications to be updated and at
21001            // that point remove a previously declared activity component that
21002            // had been set as a preferred activity.  We try to clean this up
21003            // the next time we encounter that preferred activity, but it is
21004            // possible for the user flow to never be able to return to that
21005            // situation so here we do a sanity check to make sure we haven't
21006            // left any junk around.
21007            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21008            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21009                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21010                removed.clear();
21011                for (PreferredActivity pa : pir.filterSet()) {
21012                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21013                        removed.add(pa);
21014                    }
21015                }
21016                if (removed.size() > 0) {
21017                    for (int r=0; r<removed.size(); r++) {
21018                        PreferredActivity pa = removed.get(r);
21019                        Slog.w(TAG, "Removing dangling preferred activity: "
21020                                + pa.mPref.mComponent);
21021                        pir.removeFilter(pa);
21022                    }
21023                    mSettings.writePackageRestrictionsLPr(
21024                            mSettings.mPreferredActivities.keyAt(i));
21025                }
21026            }
21027
21028            for (int userId : UserManagerService.getInstance().getUserIds()) {
21029                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21030                    grantPermissionsUserIds = ArrayUtils.appendInt(
21031                            grantPermissionsUserIds, userId);
21032                }
21033            }
21034        }
21035        sUserManager.systemReady();
21036        // If we upgraded grant all default permissions before kicking off.
21037        for (int userId : grantPermissionsUserIds) {
21038            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21039        }
21040
21041        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21042            // If we did not grant default permissions, we preload from this the
21043            // default permission exceptions lazily to ensure we don't hit the
21044            // disk on a new user creation.
21045            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21046        }
21047
21048        // Now that we've scanned all packages, and granted any default
21049        // permissions, ensure permissions are updated. Beware of dragons if you
21050        // try optimizing this.
21051        synchronized (mPackages) {
21052            mPermissionManager.updateAllPermissions(
21053                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
21054                    mPermissionCallback);
21055        }
21056
21057        // Kick off any messages waiting for system ready
21058        if (mPostSystemReadyMessages != null) {
21059            for (Message msg : mPostSystemReadyMessages) {
21060                msg.sendToTarget();
21061            }
21062            mPostSystemReadyMessages = null;
21063        }
21064
21065        // Watch for external volumes that come and go over time
21066        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21067        storage.registerListener(mStorageListener);
21068
21069        mInstallerService.systemReady();
21070        mPackageDexOptimizer.systemReady();
21071
21072        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21073                StorageManagerInternal.class);
21074        StorageManagerInternal.addExternalStoragePolicy(
21075                new StorageManagerInternal.ExternalStorageMountPolicy() {
21076            @Override
21077            public int getMountMode(int uid, String packageName) {
21078                if (Process.isIsolated(uid)) {
21079                    return Zygote.MOUNT_EXTERNAL_NONE;
21080                }
21081                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21082                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21083                }
21084                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21085                    return Zygote.MOUNT_EXTERNAL_READ;
21086                }
21087                return Zygote.MOUNT_EXTERNAL_WRITE;
21088            }
21089
21090            @Override
21091            public boolean hasExternalStorage(int uid, String packageName) {
21092                return true;
21093            }
21094        });
21095
21096        // Now that we're mostly running, clean up stale users and apps
21097        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21098        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21099
21100        mPermissionManager.systemReady();
21101
21102        if (mInstantAppResolverConnection != null) {
21103            mContext.registerReceiver(new BroadcastReceiver() {
21104                @Override
21105                public void onReceive(Context context, Intent intent) {
21106                    mInstantAppResolverConnection.optimisticBind();
21107                    mContext.unregisterReceiver(this);
21108                }
21109            }, new IntentFilter(Intent.ACTION_BOOT_COMPLETED));
21110        }
21111    }
21112
21113    public void waitForAppDataPrepared() {
21114        if (mPrepareAppDataFuture == null) {
21115            return;
21116        }
21117        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21118        mPrepareAppDataFuture = null;
21119    }
21120
21121    @Override
21122    public boolean isSafeMode() {
21123        // allow instant applications
21124        return mSafeMode;
21125    }
21126
21127    @Override
21128    public boolean hasSystemUidErrors() {
21129        // allow instant applications
21130        return mHasSystemUidErrors;
21131    }
21132
21133    static String arrayToString(int[] array) {
21134        StringBuffer buf = new StringBuffer(128);
21135        buf.append('[');
21136        if (array != null) {
21137            for (int i=0; i<array.length; i++) {
21138                if (i > 0) buf.append(", ");
21139                buf.append(array[i]);
21140            }
21141        }
21142        buf.append(']');
21143        return buf.toString();
21144    }
21145
21146    @Override
21147    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21148            FileDescriptor err, String[] args, ShellCallback callback,
21149            ResultReceiver resultReceiver) {
21150        (new PackageManagerShellCommand(this)).exec(
21151                this, in, out, err, args, callback, resultReceiver);
21152    }
21153
21154    @Override
21155    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21156        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21157
21158        DumpState dumpState = new DumpState();
21159        boolean fullPreferred = false;
21160        boolean checkin = false;
21161
21162        String packageName = null;
21163        ArraySet<String> permissionNames = null;
21164
21165        int opti = 0;
21166        while (opti < args.length) {
21167            String opt = args[opti];
21168            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21169                break;
21170            }
21171            opti++;
21172
21173            if ("-a".equals(opt)) {
21174                // Right now we only know how to print all.
21175            } else if ("-h".equals(opt)) {
21176                pw.println("Package manager dump options:");
21177                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21178                pw.println("    --checkin: dump for a checkin");
21179                pw.println("    -f: print details of intent filters");
21180                pw.println("    -h: print this help");
21181                pw.println("  cmd may be one of:");
21182                pw.println("    l[ibraries]: list known shared libraries");
21183                pw.println("    f[eatures]: list device features");
21184                pw.println("    k[eysets]: print known keysets");
21185                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21186                pw.println("    perm[issions]: dump permissions");
21187                pw.println("    permission [name ...]: dump declaration and use of given permission");
21188                pw.println("    pref[erred]: print preferred package settings");
21189                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21190                pw.println("    prov[iders]: dump content providers");
21191                pw.println("    p[ackages]: dump installed packages");
21192                pw.println("    s[hared-users]: dump shared user IDs");
21193                pw.println("    m[essages]: print collected runtime messages");
21194                pw.println("    v[erifiers]: print package verifier info");
21195                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21196                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21197                pw.println("    version: print database version info");
21198                pw.println("    write: write current settings now");
21199                pw.println("    installs: details about install sessions");
21200                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21201                pw.println("    dexopt: dump dexopt state");
21202                pw.println("    compiler-stats: dump compiler statistics");
21203                pw.println("    service-permissions: dump permissions required by services");
21204                pw.println("    <package.name>: info about given package");
21205                return;
21206            } else if ("--checkin".equals(opt)) {
21207                checkin = true;
21208            } else if ("-f".equals(opt)) {
21209                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21210            } else if ("--proto".equals(opt)) {
21211                dumpProto(fd);
21212                return;
21213            } else {
21214                pw.println("Unknown argument: " + opt + "; use -h for help");
21215            }
21216        }
21217
21218        // Is the caller requesting to dump a particular piece of data?
21219        if (opti < args.length) {
21220            String cmd = args[opti];
21221            opti++;
21222            // Is this a package name?
21223            if ("android".equals(cmd) || cmd.contains(".")) {
21224                packageName = cmd;
21225                // When dumping a single package, we always dump all of its
21226                // filter information since the amount of data will be reasonable.
21227                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21228            } else if ("check-permission".equals(cmd)) {
21229                if (opti >= args.length) {
21230                    pw.println("Error: check-permission missing permission argument");
21231                    return;
21232                }
21233                String perm = args[opti];
21234                opti++;
21235                if (opti >= args.length) {
21236                    pw.println("Error: check-permission missing package argument");
21237                    return;
21238                }
21239
21240                String pkg = args[opti];
21241                opti++;
21242                int user = UserHandle.getUserId(Binder.getCallingUid());
21243                if (opti < args.length) {
21244                    try {
21245                        user = Integer.parseInt(args[opti]);
21246                    } catch (NumberFormatException e) {
21247                        pw.println("Error: check-permission user argument is not a number: "
21248                                + args[opti]);
21249                        return;
21250                    }
21251                }
21252
21253                // Normalize package name to handle renamed packages and static libs
21254                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21255
21256                pw.println(checkPermission(perm, pkg, user));
21257                return;
21258            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21259                dumpState.setDump(DumpState.DUMP_LIBS);
21260            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21261                dumpState.setDump(DumpState.DUMP_FEATURES);
21262            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21263                if (opti >= args.length) {
21264                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21265                            | DumpState.DUMP_SERVICE_RESOLVERS
21266                            | DumpState.DUMP_RECEIVER_RESOLVERS
21267                            | DumpState.DUMP_CONTENT_RESOLVERS);
21268                } else {
21269                    while (opti < args.length) {
21270                        String name = args[opti];
21271                        if ("a".equals(name) || "activity".equals(name)) {
21272                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21273                        } else if ("s".equals(name) || "service".equals(name)) {
21274                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21275                        } else if ("r".equals(name) || "receiver".equals(name)) {
21276                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21277                        } else if ("c".equals(name) || "content".equals(name)) {
21278                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21279                        } else {
21280                            pw.println("Error: unknown resolver table type: " + name);
21281                            return;
21282                        }
21283                        opti++;
21284                    }
21285                }
21286            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21287                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21288            } else if ("permission".equals(cmd)) {
21289                if (opti >= args.length) {
21290                    pw.println("Error: permission requires permission name");
21291                    return;
21292                }
21293                permissionNames = new ArraySet<>();
21294                while (opti < args.length) {
21295                    permissionNames.add(args[opti]);
21296                    opti++;
21297                }
21298                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21299                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21300            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21301                dumpState.setDump(DumpState.DUMP_PREFERRED);
21302            } else if ("preferred-xml".equals(cmd)) {
21303                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21304                if (opti < args.length && "--full".equals(args[opti])) {
21305                    fullPreferred = true;
21306                    opti++;
21307                }
21308            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21309                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21310            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21311                dumpState.setDump(DumpState.DUMP_PACKAGES);
21312            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21313                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21314            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21315                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21316            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21317                dumpState.setDump(DumpState.DUMP_MESSAGES);
21318            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21319                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21320            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21321                    || "intent-filter-verifiers".equals(cmd)) {
21322                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21323            } else if ("version".equals(cmd)) {
21324                dumpState.setDump(DumpState.DUMP_VERSION);
21325            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21326                dumpState.setDump(DumpState.DUMP_KEYSETS);
21327            } else if ("installs".equals(cmd)) {
21328                dumpState.setDump(DumpState.DUMP_INSTALLS);
21329            } else if ("frozen".equals(cmd)) {
21330                dumpState.setDump(DumpState.DUMP_FROZEN);
21331            } else if ("volumes".equals(cmd)) {
21332                dumpState.setDump(DumpState.DUMP_VOLUMES);
21333            } else if ("dexopt".equals(cmd)) {
21334                dumpState.setDump(DumpState.DUMP_DEXOPT);
21335            } else if ("compiler-stats".equals(cmd)) {
21336                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21337            } else if ("changes".equals(cmd)) {
21338                dumpState.setDump(DumpState.DUMP_CHANGES);
21339            } else if ("service-permissions".equals(cmd)) {
21340                dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS);
21341            } else if ("write".equals(cmd)) {
21342                synchronized (mPackages) {
21343                    mSettings.writeLPr();
21344                    pw.println("Settings written.");
21345                    return;
21346                }
21347            }
21348        }
21349
21350        if (checkin) {
21351            pw.println("vers,1");
21352        }
21353
21354        // reader
21355        synchronized (mPackages) {
21356            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21357                if (!checkin) {
21358                    if (dumpState.onTitlePrinted())
21359                        pw.println();
21360                    pw.println("Database versions:");
21361                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21362                }
21363            }
21364
21365            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21366                if (!checkin) {
21367                    if (dumpState.onTitlePrinted())
21368                        pw.println();
21369                    pw.println("Verifiers:");
21370                    pw.print("  Required: ");
21371                    pw.print(mRequiredVerifierPackage);
21372                    pw.print(" (uid=");
21373                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21374                            UserHandle.USER_SYSTEM));
21375                    pw.println(")");
21376                } else if (mRequiredVerifierPackage != null) {
21377                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21378                    pw.print(",");
21379                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21380                            UserHandle.USER_SYSTEM));
21381                }
21382            }
21383
21384            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21385                    packageName == null) {
21386                if (mIntentFilterVerifierComponent != null) {
21387                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21388                    if (!checkin) {
21389                        if (dumpState.onTitlePrinted())
21390                            pw.println();
21391                        pw.println("Intent Filter Verifier:");
21392                        pw.print("  Using: ");
21393                        pw.print(verifierPackageName);
21394                        pw.print(" (uid=");
21395                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21396                                UserHandle.USER_SYSTEM));
21397                        pw.println(")");
21398                    } else if (verifierPackageName != null) {
21399                        pw.print("ifv,"); pw.print(verifierPackageName);
21400                        pw.print(",");
21401                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21402                                UserHandle.USER_SYSTEM));
21403                    }
21404                } else {
21405                    pw.println();
21406                    pw.println("No Intent Filter Verifier available!");
21407                }
21408            }
21409
21410            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21411                boolean printedHeader = false;
21412                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21413                while (it.hasNext()) {
21414                    String libName = it.next();
21415                    LongSparseArray<SharedLibraryEntry> versionedLib
21416                            = mSharedLibraries.get(libName);
21417                    if (versionedLib == null) {
21418                        continue;
21419                    }
21420                    final int versionCount = versionedLib.size();
21421                    for (int i = 0; i < versionCount; i++) {
21422                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21423                        if (!checkin) {
21424                            if (!printedHeader) {
21425                                if (dumpState.onTitlePrinted())
21426                                    pw.println();
21427                                pw.println("Libraries:");
21428                                printedHeader = true;
21429                            }
21430                            pw.print("  ");
21431                        } else {
21432                            pw.print("lib,");
21433                        }
21434                        pw.print(libEntry.info.getName());
21435                        if (libEntry.info.isStatic()) {
21436                            pw.print(" version=" + libEntry.info.getLongVersion());
21437                        }
21438                        if (!checkin) {
21439                            pw.print(" -> ");
21440                        }
21441                        if (libEntry.path != null) {
21442                            pw.print(" (jar) ");
21443                            pw.print(libEntry.path);
21444                        } else {
21445                            pw.print(" (apk) ");
21446                            pw.print(libEntry.apk);
21447                        }
21448                        pw.println();
21449                    }
21450                }
21451            }
21452
21453            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21454                if (dumpState.onTitlePrinted())
21455                    pw.println();
21456                if (!checkin) {
21457                    pw.println("Features:");
21458                }
21459
21460                synchronized (mAvailableFeatures) {
21461                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21462                        if (checkin) {
21463                            pw.print("feat,");
21464                            pw.print(feat.name);
21465                            pw.print(",");
21466                            pw.println(feat.version);
21467                        } else {
21468                            pw.print("  ");
21469                            pw.print(feat.name);
21470                            if (feat.version > 0) {
21471                                pw.print(" version=");
21472                                pw.print(feat.version);
21473                            }
21474                            pw.println();
21475                        }
21476                    }
21477                }
21478            }
21479
21480            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21481                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21482                        : "Activity Resolver Table:", "  ", packageName,
21483                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21484                    dumpState.setTitlePrinted(true);
21485                }
21486            }
21487            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21488                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21489                        : "Receiver Resolver Table:", "  ", packageName,
21490                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21491                    dumpState.setTitlePrinted(true);
21492                }
21493            }
21494            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21495                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21496                        : "Service Resolver Table:", "  ", packageName,
21497                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21498                    dumpState.setTitlePrinted(true);
21499                }
21500            }
21501            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21502                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21503                        : "Provider Resolver Table:", "  ", packageName,
21504                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21505                    dumpState.setTitlePrinted(true);
21506                }
21507            }
21508
21509            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21510                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21511                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21512                    int user = mSettings.mPreferredActivities.keyAt(i);
21513                    if (pir.dump(pw,
21514                            dumpState.getTitlePrinted()
21515                                ? "\nPreferred Activities User " + user + ":"
21516                                : "Preferred Activities User " + user + ":", "  ",
21517                            packageName, true, false)) {
21518                        dumpState.setTitlePrinted(true);
21519                    }
21520                }
21521            }
21522
21523            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21524                pw.flush();
21525                FileOutputStream fout = new FileOutputStream(fd);
21526                BufferedOutputStream str = new BufferedOutputStream(fout);
21527                XmlSerializer serializer = new FastXmlSerializer();
21528                try {
21529                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21530                    serializer.startDocument(null, true);
21531                    serializer.setFeature(
21532                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21533                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21534                    serializer.endDocument();
21535                    serializer.flush();
21536                } catch (IllegalArgumentException e) {
21537                    pw.println("Failed writing: " + e);
21538                } catch (IllegalStateException e) {
21539                    pw.println("Failed writing: " + e);
21540                } catch (IOException e) {
21541                    pw.println("Failed writing: " + e);
21542                }
21543            }
21544
21545            if (!checkin
21546                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21547                    && packageName == null) {
21548                pw.println();
21549                int count = mSettings.mPackages.size();
21550                if (count == 0) {
21551                    pw.println("No applications!");
21552                    pw.println();
21553                } else {
21554                    final String prefix = "  ";
21555                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21556                    if (allPackageSettings.size() == 0) {
21557                        pw.println("No domain preferred apps!");
21558                        pw.println();
21559                    } else {
21560                        pw.println("App verification status:");
21561                        pw.println();
21562                        count = 0;
21563                        for (PackageSetting ps : allPackageSettings) {
21564                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21565                            if (ivi == null || ivi.getPackageName() == null) continue;
21566                            pw.println(prefix + "Package: " + ivi.getPackageName());
21567                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21568                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21569                            pw.println();
21570                            count++;
21571                        }
21572                        if (count == 0) {
21573                            pw.println(prefix + "No app verification established.");
21574                            pw.println();
21575                        }
21576                        for (int userId : sUserManager.getUserIds()) {
21577                            pw.println("App linkages for user " + userId + ":");
21578                            pw.println();
21579                            count = 0;
21580                            for (PackageSetting ps : allPackageSettings) {
21581                                final long status = ps.getDomainVerificationStatusForUser(userId);
21582                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21583                                        && !DEBUG_DOMAIN_VERIFICATION) {
21584                                    continue;
21585                                }
21586                                pw.println(prefix + "Package: " + ps.name);
21587                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21588                                String statusStr = IntentFilterVerificationInfo.
21589                                        getStatusStringFromValue(status);
21590                                pw.println(prefix + "Status:  " + statusStr);
21591                                pw.println();
21592                                count++;
21593                            }
21594                            if (count == 0) {
21595                                pw.println(prefix + "No configured app linkages.");
21596                                pw.println();
21597                            }
21598                        }
21599                    }
21600                }
21601            }
21602
21603            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21604                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21605            }
21606
21607            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21608                boolean printedSomething = false;
21609                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21610                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21611                        continue;
21612                    }
21613                    if (!printedSomething) {
21614                        if (dumpState.onTitlePrinted())
21615                            pw.println();
21616                        pw.println("Registered ContentProviders:");
21617                        printedSomething = true;
21618                    }
21619                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21620                    pw.print("    "); pw.println(p.toString());
21621                }
21622                printedSomething = false;
21623                for (Map.Entry<String, PackageParser.Provider> entry :
21624                        mProvidersByAuthority.entrySet()) {
21625                    PackageParser.Provider p = entry.getValue();
21626                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21627                        continue;
21628                    }
21629                    if (!printedSomething) {
21630                        if (dumpState.onTitlePrinted())
21631                            pw.println();
21632                        pw.println("ContentProvider Authorities:");
21633                        printedSomething = true;
21634                    }
21635                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21636                    pw.print("    "); pw.println(p.toString());
21637                    if (p.info != null && p.info.applicationInfo != null) {
21638                        final String appInfo = p.info.applicationInfo.toString();
21639                        pw.print("      applicationInfo="); pw.println(appInfo);
21640                    }
21641                }
21642            }
21643
21644            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21645                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21646            }
21647
21648            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21649                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21650            }
21651
21652            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21653                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21654            }
21655
21656            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21657                if (dumpState.onTitlePrinted()) pw.println();
21658                pw.println("Package Changes:");
21659                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21660                final int K = mChangedPackages.size();
21661                for (int i = 0; i < K; i++) {
21662                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21663                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21664                    final int N = changes.size();
21665                    if (N == 0) {
21666                        pw.print("    "); pw.println("No packages changed");
21667                    } else {
21668                        for (int j = 0; j < N; j++) {
21669                            final String pkgName = changes.valueAt(j);
21670                            final int sequenceNumber = changes.keyAt(j);
21671                            pw.print("    ");
21672                            pw.print("seq=");
21673                            pw.print(sequenceNumber);
21674                            pw.print(", package=");
21675                            pw.println(pkgName);
21676                        }
21677                    }
21678                }
21679            }
21680
21681            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21682                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21683            }
21684
21685            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21686                // XXX should handle packageName != null by dumping only install data that
21687                // the given package is involved with.
21688                if (dumpState.onTitlePrinted()) pw.println();
21689
21690                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21691                ipw.println();
21692                ipw.println("Frozen packages:");
21693                ipw.increaseIndent();
21694                if (mFrozenPackages.size() == 0) {
21695                    ipw.println("(none)");
21696                } else {
21697                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21698                        ipw.println(mFrozenPackages.valueAt(i));
21699                    }
21700                }
21701                ipw.decreaseIndent();
21702            }
21703
21704            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
21705                if (dumpState.onTitlePrinted()) pw.println();
21706
21707                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21708                ipw.println();
21709                ipw.println("Loaded volumes:");
21710                ipw.increaseIndent();
21711                if (mLoadedVolumes.size() == 0) {
21712                    ipw.println("(none)");
21713                } else {
21714                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
21715                        ipw.println(mLoadedVolumes.valueAt(i));
21716                    }
21717                }
21718                ipw.decreaseIndent();
21719            }
21720
21721            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS)
21722                    && packageName == null) {
21723                if (dumpState.onTitlePrinted()) pw.println();
21724                pw.println("Service permissions:");
21725
21726                final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator();
21727                while (filterIterator.hasNext()) {
21728                    final ServiceIntentInfo info = filterIterator.next();
21729                    final ServiceInfo serviceInfo = info.service.info;
21730                    final String permission = serviceInfo.permission;
21731                    if (permission != null) {
21732                        pw.print("    ");
21733                        pw.print(serviceInfo.getComponentName().flattenToShortString());
21734                        pw.print(": ");
21735                        pw.println(permission);
21736                    }
21737                }
21738            }
21739
21740            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21741                if (dumpState.onTitlePrinted()) pw.println();
21742                dumpDexoptStateLPr(pw, packageName);
21743            }
21744
21745            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21746                if (dumpState.onTitlePrinted()) pw.println();
21747                dumpCompilerStatsLPr(pw, packageName);
21748            }
21749
21750            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21751                if (dumpState.onTitlePrinted()) pw.println();
21752                mSettings.dumpReadMessagesLPr(pw, dumpState);
21753
21754                pw.println();
21755                pw.println("Package warning messages:");
21756                dumpCriticalInfo(pw, null);
21757            }
21758
21759            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21760                dumpCriticalInfo(pw, "msg,");
21761            }
21762        }
21763
21764        // PackageInstaller should be called outside of mPackages lock
21765        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21766            // XXX should handle packageName != null by dumping only install data that
21767            // the given package is involved with.
21768            if (dumpState.onTitlePrinted()) pw.println();
21769            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21770        }
21771    }
21772
21773    private void dumpProto(FileDescriptor fd) {
21774        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21775
21776        synchronized (mPackages) {
21777            final long requiredVerifierPackageToken =
21778                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21779            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21780            proto.write(
21781                    PackageServiceDumpProto.PackageShortProto.UID,
21782                    getPackageUid(
21783                            mRequiredVerifierPackage,
21784                            MATCH_DEBUG_TRIAGED_MISSING,
21785                            UserHandle.USER_SYSTEM));
21786            proto.end(requiredVerifierPackageToken);
21787
21788            if (mIntentFilterVerifierComponent != null) {
21789                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21790                final long verifierPackageToken =
21791                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21792                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21793                proto.write(
21794                        PackageServiceDumpProto.PackageShortProto.UID,
21795                        getPackageUid(
21796                                verifierPackageName,
21797                                MATCH_DEBUG_TRIAGED_MISSING,
21798                                UserHandle.USER_SYSTEM));
21799                proto.end(verifierPackageToken);
21800            }
21801
21802            dumpSharedLibrariesProto(proto);
21803            dumpFeaturesProto(proto);
21804            mSettings.dumpPackagesProto(proto);
21805            mSettings.dumpSharedUsersProto(proto);
21806            dumpCriticalInfo(proto);
21807        }
21808        proto.flush();
21809    }
21810
21811    private void dumpFeaturesProto(ProtoOutputStream proto) {
21812        synchronized (mAvailableFeatures) {
21813            final int count = mAvailableFeatures.size();
21814            for (int i = 0; i < count; i++) {
21815                mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
21816            }
21817        }
21818    }
21819
21820    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21821        final int count = mSharedLibraries.size();
21822        for (int i = 0; i < count; i++) {
21823            final String libName = mSharedLibraries.keyAt(i);
21824            LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21825            if (versionedLib == null) {
21826                continue;
21827            }
21828            final int versionCount = versionedLib.size();
21829            for (int j = 0; j < versionCount; j++) {
21830                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21831                final long sharedLibraryToken =
21832                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21833                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21834                final boolean isJar = (libEntry.path != null);
21835                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21836                if (isJar) {
21837                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21838                } else {
21839                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21840                }
21841                proto.end(sharedLibraryToken);
21842            }
21843        }
21844    }
21845
21846    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21847        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21848        ipw.println();
21849        ipw.println("Dexopt state:");
21850        ipw.increaseIndent();
21851        Collection<PackageParser.Package> packages = null;
21852        if (packageName != null) {
21853            PackageParser.Package targetPackage = mPackages.get(packageName);
21854            if (targetPackage != null) {
21855                packages = Collections.singletonList(targetPackage);
21856            } else {
21857                ipw.println("Unable to find package: " + packageName);
21858                return;
21859            }
21860        } else {
21861            packages = mPackages.values();
21862        }
21863
21864        for (PackageParser.Package pkg : packages) {
21865            ipw.println("[" + pkg.packageName + "]");
21866            ipw.increaseIndent();
21867            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
21868                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
21869            ipw.decreaseIndent();
21870        }
21871    }
21872
21873    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21874        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21875        ipw.println();
21876        ipw.println("Compiler stats:");
21877        ipw.increaseIndent();
21878        Collection<PackageParser.Package> packages = null;
21879        if (packageName != null) {
21880            PackageParser.Package targetPackage = mPackages.get(packageName);
21881            if (targetPackage != null) {
21882                packages = Collections.singletonList(targetPackage);
21883            } else {
21884                ipw.println("Unable to find package: " + packageName);
21885                return;
21886            }
21887        } else {
21888            packages = mPackages.values();
21889        }
21890
21891        for (PackageParser.Package pkg : packages) {
21892            ipw.println("[" + pkg.packageName + "]");
21893            ipw.increaseIndent();
21894
21895            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21896            if (stats == null) {
21897                ipw.println("(No recorded stats)");
21898            } else {
21899                stats.dump(ipw);
21900            }
21901            ipw.decreaseIndent();
21902        }
21903    }
21904
21905    private String dumpDomainString(String packageName) {
21906        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21907                .getList();
21908        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21909
21910        ArraySet<String> result = new ArraySet<>();
21911        if (iviList.size() > 0) {
21912            for (IntentFilterVerificationInfo ivi : iviList) {
21913                for (String host : ivi.getDomains()) {
21914                    result.add(host);
21915                }
21916            }
21917        }
21918        if (filters != null && filters.size() > 0) {
21919            for (IntentFilter filter : filters) {
21920                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21921                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21922                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21923                    result.addAll(filter.getHostsList());
21924                }
21925            }
21926        }
21927
21928        StringBuilder sb = new StringBuilder(result.size() * 16);
21929        for (String domain : result) {
21930            if (sb.length() > 0) sb.append(" ");
21931            sb.append(domain);
21932        }
21933        return sb.toString();
21934    }
21935
21936    // ------- apps on sdcard specific code -------
21937    static final boolean DEBUG_SD_INSTALL = false;
21938
21939    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21940
21941    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21942
21943    private boolean mMediaMounted = false;
21944
21945    static String getEncryptKey() {
21946        try {
21947            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21948                    SD_ENCRYPTION_KEYSTORE_NAME);
21949            if (sdEncKey == null) {
21950                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21951                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21952                if (sdEncKey == null) {
21953                    Slog.e(TAG, "Failed to create encryption keys");
21954                    return null;
21955                }
21956            }
21957            return sdEncKey;
21958        } catch (NoSuchAlgorithmException nsae) {
21959            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21960            return null;
21961        } catch (IOException ioe) {
21962            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21963            return null;
21964        }
21965    }
21966
21967    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21968            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21969        final int size = infos.size();
21970        final String[] packageNames = new String[size];
21971        final int[] packageUids = new int[size];
21972        for (int i = 0; i < size; i++) {
21973            final ApplicationInfo info = infos.get(i);
21974            packageNames[i] = info.packageName;
21975            packageUids[i] = info.uid;
21976        }
21977        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21978                finishedReceiver);
21979    }
21980
21981    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21982            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21983        sendResourcesChangedBroadcast(mediaStatus, replacing,
21984                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21985    }
21986
21987    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21988            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21989        int size = pkgList.length;
21990        if (size > 0) {
21991            // Send broadcasts here
21992            Bundle extras = new Bundle();
21993            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21994            if (uidArr != null) {
21995                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21996            }
21997            if (replacing) {
21998                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21999            }
22000            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22001                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22002            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null);
22003        }
22004    }
22005
22006    private void loadPrivatePackages(final VolumeInfo vol) {
22007        mHandler.post(new Runnable() {
22008            @Override
22009            public void run() {
22010                loadPrivatePackagesInner(vol);
22011            }
22012        });
22013    }
22014
22015    private void loadPrivatePackagesInner(VolumeInfo vol) {
22016        final String volumeUuid = vol.fsUuid;
22017        if (TextUtils.isEmpty(volumeUuid)) {
22018            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
22019            return;
22020        }
22021
22022        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
22023        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
22024        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
22025
22026        final VersionInfo ver;
22027        final List<PackageSetting> packages;
22028        synchronized (mPackages) {
22029            ver = mSettings.findOrCreateVersion(volumeUuid);
22030            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22031        }
22032
22033        for (PackageSetting ps : packages) {
22034            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
22035            synchronized (mInstallLock) {
22036                final PackageParser.Package pkg;
22037                try {
22038                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
22039                    loaded.add(pkg.applicationInfo);
22040
22041                } catch (PackageManagerException e) {
22042                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
22043                }
22044
22045                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
22046                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
22047                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
22048                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22049                }
22050            }
22051        }
22052
22053        // Reconcile app data for all started/unlocked users
22054        final StorageManager sm = mContext.getSystemService(StorageManager.class);
22055        final UserManager um = mContext.getSystemService(UserManager.class);
22056        UserManagerInternal umInternal = getUserManagerInternal();
22057        for (UserInfo user : um.getUsers()) {
22058            final int flags;
22059            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22060                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22061            } else if (umInternal.isUserRunning(user.id)) {
22062                flags = StorageManager.FLAG_STORAGE_DE;
22063            } else {
22064                continue;
22065            }
22066
22067            try {
22068                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
22069                synchronized (mInstallLock) {
22070                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
22071                }
22072            } catch (IllegalStateException e) {
22073                // Device was probably ejected, and we'll process that event momentarily
22074                Slog.w(TAG, "Failed to prepare storage: " + e);
22075            }
22076        }
22077
22078        synchronized (mPackages) {
22079            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
22080            if (sdkUpdated) {
22081                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22082                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
22083            }
22084            mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(),
22085                    mPermissionCallback);
22086
22087            // Yay, everything is now upgraded
22088            ver.forceCurrent();
22089
22090            mSettings.writeLPr();
22091        }
22092
22093        for (PackageFreezer freezer : freezers) {
22094            freezer.close();
22095        }
22096
22097        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
22098        sendResourcesChangedBroadcast(true, false, loaded, null);
22099        mLoadedVolumes.add(vol.getId());
22100    }
22101
22102    private void unloadPrivatePackages(final VolumeInfo vol) {
22103        mHandler.post(new Runnable() {
22104            @Override
22105            public void run() {
22106                unloadPrivatePackagesInner(vol);
22107            }
22108        });
22109    }
22110
22111    private void unloadPrivatePackagesInner(VolumeInfo vol) {
22112        final String volumeUuid = vol.fsUuid;
22113        if (TextUtils.isEmpty(volumeUuid)) {
22114            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
22115            return;
22116        }
22117
22118        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
22119        synchronized (mInstallLock) {
22120        synchronized (mPackages) {
22121            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
22122            for (PackageSetting ps : packages) {
22123                if (ps.pkg == null) continue;
22124
22125                final ApplicationInfo info = ps.pkg.applicationInfo;
22126                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22127                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22128
22129                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
22130                        "unloadPrivatePackagesInner")) {
22131                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
22132                            false, null)) {
22133                        unloaded.add(info);
22134                    } else {
22135                        Slog.w(TAG, "Failed to unload " + ps.codePath);
22136                    }
22137                }
22138
22139                // Try very hard to release any references to this package
22140                // so we don't risk the system server being killed due to
22141                // open FDs
22142                AttributeCache.instance().removePackage(ps.name);
22143            }
22144
22145            mSettings.writeLPr();
22146        }
22147        }
22148
22149        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
22150        sendResourcesChangedBroadcast(false, false, unloaded, null);
22151        mLoadedVolumes.remove(vol.getId());
22152
22153        // Try very hard to release any references to this path so we don't risk
22154        // the system server being killed due to open FDs
22155        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
22156
22157        for (int i = 0; i < 3; i++) {
22158            System.gc();
22159            System.runFinalization();
22160        }
22161    }
22162
22163    private void assertPackageKnown(String volumeUuid, String packageName)
22164            throws PackageManagerException {
22165        synchronized (mPackages) {
22166            // Normalize package name to handle renamed packages
22167            packageName = normalizePackageNameLPr(packageName);
22168
22169            final PackageSetting ps = mSettings.mPackages.get(packageName);
22170            if (ps == null) {
22171                throw new PackageManagerException("Package " + packageName + " is unknown");
22172            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22173                throw new PackageManagerException(
22174                        "Package " + packageName + " found on unknown volume " + volumeUuid
22175                                + "; expected volume " + ps.volumeUuid);
22176            }
22177        }
22178    }
22179
22180    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
22181            throws PackageManagerException {
22182        synchronized (mPackages) {
22183            // Normalize package name to handle renamed packages
22184            packageName = normalizePackageNameLPr(packageName);
22185
22186            final PackageSetting ps = mSettings.mPackages.get(packageName);
22187            if (ps == null) {
22188                throw new PackageManagerException("Package " + packageName + " is unknown");
22189            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22190                throw new PackageManagerException(
22191                        "Package " + packageName + " found on unknown volume " + volumeUuid
22192                                + "; expected volume " + ps.volumeUuid);
22193            } else if (!ps.getInstalled(userId)) {
22194                throw new PackageManagerException(
22195                        "Package " + packageName + " not installed for user " + userId);
22196            }
22197        }
22198    }
22199
22200    private List<String> collectAbsoluteCodePaths() {
22201        synchronized (mPackages) {
22202            List<String> codePaths = new ArrayList<>();
22203            final int packageCount = mSettings.mPackages.size();
22204            for (int i = 0; i < packageCount; i++) {
22205                final PackageSetting ps = mSettings.mPackages.valueAt(i);
22206                codePaths.add(ps.codePath.getAbsolutePath());
22207            }
22208            return codePaths;
22209        }
22210    }
22211
22212    /**
22213     * Examine all apps present on given mounted volume, and destroy apps that
22214     * aren't expected, either due to uninstallation or reinstallation on
22215     * another volume.
22216     */
22217    private void reconcileApps(String volumeUuid) {
22218        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
22219        List<File> filesToDelete = null;
22220
22221        final File[] files = FileUtils.listFilesOrEmpty(
22222                Environment.getDataAppDirectory(volumeUuid));
22223        for (File file : files) {
22224            final boolean isPackage = (isApkFile(file) || file.isDirectory())
22225                    && !PackageInstallerService.isStageName(file.getName());
22226            if (!isPackage) {
22227                // Ignore entries which are not packages
22228                continue;
22229            }
22230
22231            String absolutePath = file.getAbsolutePath();
22232
22233            boolean pathValid = false;
22234            final int absoluteCodePathCount = absoluteCodePaths.size();
22235            for (int i = 0; i < absoluteCodePathCount; i++) {
22236                String absoluteCodePath = absoluteCodePaths.get(i);
22237                if (absolutePath.startsWith(absoluteCodePath)) {
22238                    pathValid = true;
22239                    break;
22240                }
22241            }
22242
22243            if (!pathValid) {
22244                if (filesToDelete == null) {
22245                    filesToDelete = new ArrayList<>();
22246                }
22247                filesToDelete.add(file);
22248            }
22249        }
22250
22251        if (filesToDelete != null) {
22252            final int fileToDeleteCount = filesToDelete.size();
22253            for (int i = 0; i < fileToDeleteCount; i++) {
22254                File fileToDelete = filesToDelete.get(i);
22255                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22256                synchronized (mInstallLock) {
22257                    removeCodePathLI(fileToDelete);
22258                }
22259            }
22260        }
22261    }
22262
22263    /**
22264     * Reconcile all app data for the given user.
22265     * <p>
22266     * Verifies that directories exist and that ownership and labeling is
22267     * correct for all installed apps on all mounted volumes.
22268     */
22269    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22270        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22271        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22272            final String volumeUuid = vol.getFsUuid();
22273            synchronized (mInstallLock) {
22274                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22275            }
22276        }
22277    }
22278
22279    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22280            boolean migrateAppData) {
22281        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22282    }
22283
22284    /**
22285     * Reconcile all app data on given mounted volume.
22286     * <p>
22287     * Destroys app data that isn't expected, either due to uninstallation or
22288     * reinstallation on another volume.
22289     * <p>
22290     * Verifies that directories exist and that ownership and labeling is
22291     * correct for all installed apps.
22292     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22293     */
22294    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22295            boolean migrateAppData, boolean onlyCoreApps) {
22296        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22297                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22298        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22299
22300        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22301        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22302
22303        // First look for stale data that doesn't belong, and check if things
22304        // have changed since we did our last restorecon
22305        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22306            if (StorageManager.isFileEncryptedNativeOrEmulated()
22307                    && !StorageManager.isUserKeyUnlocked(userId)) {
22308                throw new RuntimeException(
22309                        "Yikes, someone asked us to reconcile CE storage while " + userId
22310                                + " was still locked; this would have caused massive data loss!");
22311            }
22312
22313            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22314            for (File file : files) {
22315                final String packageName = file.getName();
22316                try {
22317                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22318                } catch (PackageManagerException e) {
22319                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22320                    try {
22321                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22322                                StorageManager.FLAG_STORAGE_CE, 0);
22323                    } catch (InstallerException e2) {
22324                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22325                    }
22326                }
22327            }
22328        }
22329        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22330            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22331            for (File file : files) {
22332                final String packageName = file.getName();
22333                try {
22334                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22335                } catch (PackageManagerException e) {
22336                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22337                    try {
22338                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22339                                StorageManager.FLAG_STORAGE_DE, 0);
22340                    } catch (InstallerException e2) {
22341                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22342                    }
22343                }
22344            }
22345        }
22346
22347        // Ensure that data directories are ready to roll for all packages
22348        // installed for this volume and user
22349        final List<PackageSetting> packages;
22350        synchronized (mPackages) {
22351            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22352        }
22353        int preparedCount = 0;
22354        for (PackageSetting ps : packages) {
22355            final String packageName = ps.name;
22356            if (ps.pkg == null) {
22357                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22358                // TODO: might be due to legacy ASEC apps; we should circle back
22359                // and reconcile again once they're scanned
22360                continue;
22361            }
22362            // Skip non-core apps if requested
22363            if (onlyCoreApps && !ps.pkg.coreApp) {
22364                result.add(packageName);
22365                continue;
22366            }
22367
22368            if (ps.getInstalled(userId)) {
22369                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22370                preparedCount++;
22371            }
22372        }
22373
22374        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22375        return result;
22376    }
22377
22378    /**
22379     * Prepare app data for the given app just after it was installed or
22380     * upgraded. This method carefully only touches users that it's installed
22381     * for, and it forces a restorecon to handle any seinfo changes.
22382     * <p>
22383     * Verifies that directories exist and that ownership and labeling is
22384     * correct for all installed apps. If there is an ownership mismatch, it
22385     * will try recovering system apps by wiping data; third-party app data is
22386     * left intact.
22387     * <p>
22388     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22389     */
22390    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22391        final PackageSetting ps;
22392        synchronized (mPackages) {
22393            ps = mSettings.mPackages.get(pkg.packageName);
22394            mSettings.writeKernelMappingLPr(ps);
22395        }
22396
22397        final UserManager um = mContext.getSystemService(UserManager.class);
22398        UserManagerInternal umInternal = getUserManagerInternal();
22399        for (UserInfo user : um.getUsers()) {
22400            final int flags;
22401            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22402                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22403            } else if (umInternal.isUserRunning(user.id)) {
22404                flags = StorageManager.FLAG_STORAGE_DE;
22405            } else {
22406                continue;
22407            }
22408
22409            if (ps.getInstalled(user.id)) {
22410                // TODO: when user data is locked, mark that we're still dirty
22411                prepareAppDataLIF(pkg, user.id, flags);
22412            }
22413        }
22414    }
22415
22416    /**
22417     * Prepare app data for the given app.
22418     * <p>
22419     * Verifies that directories exist and that ownership and labeling is
22420     * correct for all installed apps. If there is an ownership mismatch, this
22421     * will try recovering system apps by wiping data; third-party app data is
22422     * left intact.
22423     */
22424    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22425        if (pkg == null) {
22426            Slog.wtf(TAG, "Package was null!", new Throwable());
22427            return;
22428        }
22429        prepareAppDataLeafLIF(pkg, userId, flags);
22430        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22431        for (int i = 0; i < childCount; i++) {
22432            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22433        }
22434    }
22435
22436    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22437            boolean maybeMigrateAppData) {
22438        prepareAppDataLIF(pkg, userId, flags);
22439
22440        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22441            // We may have just shuffled around app data directories, so
22442            // prepare them one more time
22443            prepareAppDataLIF(pkg, userId, flags);
22444        }
22445    }
22446
22447    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22448        if (DEBUG_APP_DATA) {
22449            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22450                    + Integer.toHexString(flags));
22451        }
22452
22453        final PackageSetting ps;
22454        synchronized (mPackages) {
22455            ps = mSettings.mPackages.get(pkg.packageName);
22456        }
22457        final String volumeUuid = pkg.volumeUuid;
22458        final String packageName = pkg.packageName;
22459        final ApplicationInfo app = (ps == null)
22460                ? pkg.applicationInfo
22461                : PackageParser.generateApplicationInfo(pkg, 0, ps.readUserState(userId), userId);
22462
22463        final int appId = UserHandle.getAppId(app.uid);
22464
22465        Preconditions.checkNotNull(app.seInfo);
22466
22467        final String seInfo = app.seInfo + (app.seInfoUser != null ? app.seInfoUser : "");
22468        long ceDataInode = -1;
22469        try {
22470            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22471                    appId, seInfo, app.targetSdkVersion);
22472        } catch (InstallerException e) {
22473            if (app.isSystemApp()) {
22474                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22475                        + ", but trying to recover: " + e);
22476                destroyAppDataLeafLIF(pkg, userId, flags);
22477                try {
22478                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22479                            appId, seInfo, app.targetSdkVersion);
22480                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22481                } catch (InstallerException e2) {
22482                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22483                }
22484            } else {
22485                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22486            }
22487        }
22488        // Prepare the application profiles only for upgrades and first boot (so that we don't
22489        // repeat the same operation at each boot).
22490        // We only have to cover the upgrade and first boot here because for app installs we
22491        // prepare the profiles before invoking dexopt (in installPackageLI).
22492        //
22493        // We also have to cover non system users because we do not call the usual install package
22494        // methods for them.
22495        if (mIsUpgrade || mFirstBoot || (userId != UserHandle.USER_SYSTEM)) {
22496            mArtManagerService.prepareAppProfiles(pkg, userId);
22497        }
22498
22499        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22500            // TODO: mark this structure as dirty so we persist it!
22501            synchronized (mPackages) {
22502                if (ps != null) {
22503                    ps.setCeDataInode(ceDataInode, userId);
22504                }
22505            }
22506        }
22507
22508        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22509    }
22510
22511    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22512        if (pkg == null) {
22513            Slog.wtf(TAG, "Package was null!", new Throwable());
22514            return;
22515        }
22516        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22517        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22518        for (int i = 0; i < childCount; i++) {
22519            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22520        }
22521    }
22522
22523    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22524        final String volumeUuid = pkg.volumeUuid;
22525        final String packageName = pkg.packageName;
22526        final ApplicationInfo app = pkg.applicationInfo;
22527
22528        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22529            // Create a native library symlink only if we have native libraries
22530            // and if the native libraries are 32 bit libraries. We do not provide
22531            // this symlink for 64 bit libraries.
22532            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22533                final String nativeLibPath = app.nativeLibraryDir;
22534                try {
22535                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22536                            nativeLibPath, userId);
22537                } catch (InstallerException e) {
22538                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22539                }
22540            }
22541        }
22542    }
22543
22544    /**
22545     * For system apps on non-FBE devices, this method migrates any existing
22546     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22547     * requested by the app.
22548     */
22549    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22550        if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated()
22551                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22552            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22553                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22554            try {
22555                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22556                        storageTarget);
22557            } catch (InstallerException e) {
22558                logCriticalInfo(Log.WARN,
22559                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22560            }
22561            return true;
22562        } else {
22563            return false;
22564        }
22565    }
22566
22567    public PackageFreezer freezePackage(String packageName, String killReason) {
22568        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22569    }
22570
22571    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22572        return new PackageFreezer(packageName, userId, killReason);
22573    }
22574
22575    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22576            String killReason) {
22577        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22578    }
22579
22580    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22581            String killReason) {
22582        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22583            return new PackageFreezer();
22584        } else {
22585            return freezePackage(packageName, userId, killReason);
22586        }
22587    }
22588
22589    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22590            String killReason) {
22591        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22592    }
22593
22594    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22595            String killReason) {
22596        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22597            return new PackageFreezer();
22598        } else {
22599            return freezePackage(packageName, userId, killReason);
22600        }
22601    }
22602
22603    /**
22604     * Class that freezes and kills the given package upon creation, and
22605     * unfreezes it upon closing. This is typically used when doing surgery on
22606     * app code/data to prevent the app from running while you're working.
22607     */
22608    private class PackageFreezer implements AutoCloseable {
22609        private final String mPackageName;
22610        private final PackageFreezer[] mChildren;
22611
22612        private final boolean mWeFroze;
22613
22614        private final AtomicBoolean mClosed = new AtomicBoolean();
22615        private final CloseGuard mCloseGuard = CloseGuard.get();
22616
22617        /**
22618         * Create and return a stub freezer that doesn't actually do anything,
22619         * typically used when someone requested
22620         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22621         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22622         */
22623        public PackageFreezer() {
22624            mPackageName = null;
22625            mChildren = null;
22626            mWeFroze = false;
22627            mCloseGuard.open("close");
22628        }
22629
22630        public PackageFreezer(String packageName, int userId, String killReason) {
22631            synchronized (mPackages) {
22632                mPackageName = packageName;
22633                mWeFroze = mFrozenPackages.add(mPackageName);
22634
22635                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22636                if (ps != null) {
22637                    killApplication(ps.name, ps.appId, userId, killReason);
22638                }
22639
22640                final PackageParser.Package p = mPackages.get(packageName);
22641                if (p != null && p.childPackages != null) {
22642                    final int N = p.childPackages.size();
22643                    mChildren = new PackageFreezer[N];
22644                    for (int i = 0; i < N; i++) {
22645                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22646                                userId, killReason);
22647                    }
22648                } else {
22649                    mChildren = null;
22650                }
22651            }
22652            mCloseGuard.open("close");
22653        }
22654
22655        @Override
22656        protected void finalize() throws Throwable {
22657            try {
22658                if (mCloseGuard != null) {
22659                    mCloseGuard.warnIfOpen();
22660                }
22661
22662                close();
22663            } finally {
22664                super.finalize();
22665            }
22666        }
22667
22668        @Override
22669        public void close() {
22670            mCloseGuard.close();
22671            if (mClosed.compareAndSet(false, true)) {
22672                synchronized (mPackages) {
22673                    if (mWeFroze) {
22674                        mFrozenPackages.remove(mPackageName);
22675                    }
22676
22677                    if (mChildren != null) {
22678                        for (PackageFreezer freezer : mChildren) {
22679                            freezer.close();
22680                        }
22681                    }
22682                }
22683            }
22684        }
22685    }
22686
22687    /**
22688     * Verify that given package is currently frozen.
22689     */
22690    private void checkPackageFrozen(String packageName) {
22691        synchronized (mPackages) {
22692            if (!mFrozenPackages.contains(packageName)) {
22693                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22694            }
22695        }
22696    }
22697
22698    @Override
22699    public int movePackage(final String packageName, final String volumeUuid) {
22700        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22701
22702        final int callingUid = Binder.getCallingUid();
22703        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
22704        final int moveId = mNextMoveId.getAndIncrement();
22705        mHandler.post(new Runnable() {
22706            @Override
22707            public void run() {
22708                try {
22709                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
22710                } catch (PackageManagerException e) {
22711                    Slog.w(TAG, "Failed to move " + packageName, e);
22712                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
22713                }
22714            }
22715        });
22716        return moveId;
22717    }
22718
22719    private void movePackageInternal(final String packageName, final String volumeUuid,
22720            final int moveId, final int callingUid, UserHandle user)
22721                    throws PackageManagerException {
22722        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22723        final PackageManager pm = mContext.getPackageManager();
22724
22725        final boolean currentAsec;
22726        final String currentVolumeUuid;
22727        final File codeFile;
22728        final String installerPackageName;
22729        final String packageAbiOverride;
22730        final int appId;
22731        final String seinfo;
22732        final String label;
22733        final int targetSdkVersion;
22734        final PackageFreezer freezer;
22735        final int[] installedUserIds;
22736
22737        // reader
22738        synchronized (mPackages) {
22739            final PackageParser.Package pkg = mPackages.get(packageName);
22740            final PackageSetting ps = mSettings.mPackages.get(packageName);
22741            if (pkg == null
22742                    || ps == null
22743                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
22744                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22745            }
22746            if (pkg.applicationInfo.isSystemApp()) {
22747                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22748                        "Cannot move system application");
22749            }
22750
22751            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22752            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22753                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22754            if (isInternalStorage && !allow3rdPartyOnInternal) {
22755                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22756                        "3rd party apps are not allowed on internal storage");
22757            }
22758
22759            if (pkg.applicationInfo.isExternalAsec()) {
22760                currentAsec = true;
22761                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22762            } else if (pkg.applicationInfo.isForwardLocked()) {
22763                currentAsec = true;
22764                currentVolumeUuid = "forward_locked";
22765            } else {
22766                currentAsec = false;
22767                currentVolumeUuid = ps.volumeUuid;
22768
22769                final File probe = new File(pkg.codePath);
22770                final File probeOat = new File(probe, "oat");
22771                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22772                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22773                            "Move only supported for modern cluster style installs");
22774                }
22775            }
22776
22777            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22778                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22779                        "Package already moved to " + volumeUuid);
22780            }
22781            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22782                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22783                        "Device admin cannot be moved");
22784            }
22785
22786            if (mFrozenPackages.contains(packageName)) {
22787                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22788                        "Failed to move already frozen package");
22789            }
22790
22791            codeFile = new File(pkg.codePath);
22792            installerPackageName = ps.installerPackageName;
22793            packageAbiOverride = ps.cpuAbiOverrideString;
22794            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22795            seinfo = pkg.applicationInfo.seInfo;
22796            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22797            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22798            freezer = freezePackage(packageName, "movePackageInternal");
22799            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22800        }
22801
22802        final Bundle extras = new Bundle();
22803        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22804        extras.putString(Intent.EXTRA_TITLE, label);
22805        mMoveCallbacks.notifyCreated(moveId, extras);
22806
22807        int installFlags;
22808        final boolean moveCompleteApp;
22809        final File measurePath;
22810
22811        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22812            installFlags = INSTALL_INTERNAL;
22813            moveCompleteApp = !currentAsec;
22814            measurePath = Environment.getDataAppDirectory(volumeUuid);
22815        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22816            installFlags = INSTALL_EXTERNAL;
22817            moveCompleteApp = false;
22818            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22819        } else {
22820            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22821            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22822                    || !volume.isMountedWritable()) {
22823                freezer.close();
22824                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22825                        "Move location not mounted private volume");
22826            }
22827
22828            Preconditions.checkState(!currentAsec);
22829
22830            installFlags = INSTALL_INTERNAL;
22831            moveCompleteApp = true;
22832            measurePath = Environment.getDataAppDirectory(volumeUuid);
22833        }
22834
22835        // If we're moving app data around, we need all the users unlocked
22836        if (moveCompleteApp) {
22837            for (int userId : installedUserIds) {
22838                if (StorageManager.isFileEncryptedNativeOrEmulated()
22839                        && !StorageManager.isUserKeyUnlocked(userId)) {
22840                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
22841                            "User " + userId + " must be unlocked");
22842                }
22843            }
22844        }
22845
22846        final PackageStats stats = new PackageStats(null, -1);
22847        synchronized (mInstaller) {
22848            for (int userId : installedUserIds) {
22849                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22850                    freezer.close();
22851                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22852                            "Failed to measure package size");
22853                }
22854            }
22855        }
22856
22857        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22858                + stats.dataSize);
22859
22860        final long startFreeBytes = measurePath.getUsableSpace();
22861        final long sizeBytes;
22862        if (moveCompleteApp) {
22863            sizeBytes = stats.codeSize + stats.dataSize;
22864        } else {
22865            sizeBytes = stats.codeSize;
22866        }
22867
22868        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22869            freezer.close();
22870            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22871                    "Not enough free space to move");
22872        }
22873
22874        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22875
22876        final CountDownLatch installedLatch = new CountDownLatch(1);
22877        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22878            @Override
22879            public void onUserActionRequired(Intent intent) throws RemoteException {
22880                throw new IllegalStateException();
22881            }
22882
22883            @Override
22884            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22885                    Bundle extras) throws RemoteException {
22886                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22887                        + PackageManager.installStatusToString(returnCode, msg));
22888
22889                installedLatch.countDown();
22890                freezer.close();
22891
22892                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22893                switch (status) {
22894                    case PackageInstaller.STATUS_SUCCESS:
22895                        mMoveCallbacks.notifyStatusChanged(moveId,
22896                                PackageManager.MOVE_SUCCEEDED);
22897                        break;
22898                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22899                        mMoveCallbacks.notifyStatusChanged(moveId,
22900                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22901                        break;
22902                    default:
22903                        mMoveCallbacks.notifyStatusChanged(moveId,
22904                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22905                        break;
22906                }
22907            }
22908        };
22909
22910        final MoveInfo move;
22911        if (moveCompleteApp) {
22912            // Kick off a thread to report progress estimates
22913            new Thread() {
22914                @Override
22915                public void run() {
22916                    while (true) {
22917                        try {
22918                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22919                                break;
22920                            }
22921                        } catch (InterruptedException ignored) {
22922                        }
22923
22924                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22925                        final int progress = 10 + (int) MathUtils.constrain(
22926                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22927                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22928                    }
22929                }
22930            }.start();
22931
22932            final String dataAppName = codeFile.getName();
22933            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22934                    dataAppName, appId, seinfo, targetSdkVersion);
22935        } else {
22936            move = null;
22937        }
22938
22939        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22940
22941        final Message msg = mHandler.obtainMessage(INIT_COPY);
22942        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22943        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22944                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22945                packageAbiOverride, null /*grantedPermissions*/,
22946                PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN);
22947        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22948        msg.obj = params;
22949
22950        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22951                System.identityHashCode(msg.obj));
22952        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22953                System.identityHashCode(msg.obj));
22954
22955        mHandler.sendMessage(msg);
22956    }
22957
22958    @Override
22959    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22960        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22961
22962        final int realMoveId = mNextMoveId.getAndIncrement();
22963        final Bundle extras = new Bundle();
22964        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22965        mMoveCallbacks.notifyCreated(realMoveId, extras);
22966
22967        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22968            @Override
22969            public void onCreated(int moveId, Bundle extras) {
22970                // Ignored
22971            }
22972
22973            @Override
22974            public void onStatusChanged(int moveId, int status, long estMillis) {
22975                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22976            }
22977        };
22978
22979        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22980        storage.setPrimaryStorageUuid(volumeUuid, callback);
22981        return realMoveId;
22982    }
22983
22984    @Override
22985    public int getMoveStatus(int moveId) {
22986        mContext.enforceCallingOrSelfPermission(
22987                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22988        return mMoveCallbacks.mLastStatus.get(moveId);
22989    }
22990
22991    @Override
22992    public void registerMoveCallback(IPackageMoveObserver callback) {
22993        mContext.enforceCallingOrSelfPermission(
22994                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22995        mMoveCallbacks.register(callback);
22996    }
22997
22998    @Override
22999    public void unregisterMoveCallback(IPackageMoveObserver callback) {
23000        mContext.enforceCallingOrSelfPermission(
23001                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23002        mMoveCallbacks.unregister(callback);
23003    }
23004
23005    @Override
23006    public boolean setInstallLocation(int loc) {
23007        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
23008                null);
23009        if (getInstallLocation() == loc) {
23010            return true;
23011        }
23012        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
23013                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
23014            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
23015                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
23016            return true;
23017        }
23018        return false;
23019   }
23020
23021    @Override
23022    public int getInstallLocation() {
23023        // allow instant app access
23024        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
23025                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
23026                PackageHelper.APP_INSTALL_AUTO);
23027    }
23028
23029    /** Called by UserManagerService */
23030    void cleanUpUser(UserManagerService userManager, int userHandle) {
23031        synchronized (mPackages) {
23032            mDirtyUsers.remove(userHandle);
23033            mUserNeedsBadging.delete(userHandle);
23034            mSettings.removeUserLPw(userHandle);
23035            mPendingBroadcasts.remove(userHandle);
23036            mInstantAppRegistry.onUserRemovedLPw(userHandle);
23037            removeUnusedPackagesLPw(userManager, userHandle);
23038        }
23039    }
23040
23041    /**
23042     * We're removing userHandle and would like to remove any downloaded packages
23043     * that are no longer in use by any other user.
23044     * @param userHandle the user being removed
23045     */
23046    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
23047        final boolean DEBUG_CLEAN_APKS = false;
23048        int [] users = userManager.getUserIds();
23049        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
23050        while (psit.hasNext()) {
23051            PackageSetting ps = psit.next();
23052            if (ps.pkg == null) {
23053                continue;
23054            }
23055            final String packageName = ps.pkg.packageName;
23056            // Skip over if system app
23057            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23058                continue;
23059            }
23060            if (DEBUG_CLEAN_APKS) {
23061                Slog.i(TAG, "Checking package " + packageName);
23062            }
23063            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
23064            if (keep) {
23065                if (DEBUG_CLEAN_APKS) {
23066                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
23067                }
23068            } else {
23069                for (int i = 0; i < users.length; i++) {
23070                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
23071                        keep = true;
23072                        if (DEBUG_CLEAN_APKS) {
23073                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
23074                                    + users[i]);
23075                        }
23076                        break;
23077                    }
23078                }
23079            }
23080            if (!keep) {
23081                if (DEBUG_CLEAN_APKS) {
23082                    Slog.i(TAG, "  Removing package " + packageName);
23083                }
23084                mHandler.post(new Runnable() {
23085                    public void run() {
23086                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23087                                userHandle, 0);
23088                    } //end run
23089                });
23090            }
23091        }
23092    }
23093
23094    /** Called by UserManagerService */
23095    void createNewUser(int userId, String[] disallowedPackages) {
23096        synchronized (mInstallLock) {
23097            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
23098        }
23099        synchronized (mPackages) {
23100            scheduleWritePackageRestrictionsLocked(userId);
23101            scheduleWritePackageListLocked(userId);
23102            applyFactoryDefaultBrowserLPw(userId);
23103            primeDomainVerificationsLPw(userId);
23104        }
23105    }
23106
23107    void onNewUserCreated(final int userId) {
23108        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
23109        synchronized(mPackages) {
23110            // If permission review for legacy apps is required, we represent
23111            // dagerous permissions for such apps as always granted runtime
23112            // permissions to keep per user flag state whether review is needed.
23113            // Hence, if a new user is added we have to propagate dangerous
23114            // permission grants for these legacy apps.
23115            if (mSettings.mPermissions.mPermissionReviewRequired) {
23116// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG
23117                mPermissionManager.updateAllPermissions(
23118                        StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(),
23119                        mPermissionCallback);
23120            }
23121        }
23122    }
23123
23124    @Override
23125    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
23126        mContext.enforceCallingOrSelfPermission(
23127                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
23128                "Only package verification agents can read the verifier device identity");
23129
23130        synchronized (mPackages) {
23131            return mSettings.getVerifierDeviceIdentityLPw();
23132        }
23133    }
23134
23135    @Override
23136    public void setPermissionEnforced(String permission, boolean enforced) {
23137        // TODO: Now that we no longer change GID for storage, this should to away.
23138        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
23139                "setPermissionEnforced");
23140        if (READ_EXTERNAL_STORAGE.equals(permission)) {
23141            synchronized (mPackages) {
23142                if (mSettings.mReadExternalStorageEnforced == null
23143                        || mSettings.mReadExternalStorageEnforced != enforced) {
23144                    mSettings.mReadExternalStorageEnforced =
23145                            enforced ? Boolean.TRUE : Boolean.FALSE;
23146                    mSettings.writeLPr();
23147                }
23148            }
23149            // kill any non-foreground processes so we restart them and
23150            // grant/revoke the GID.
23151            final IActivityManager am = ActivityManager.getService();
23152            if (am != null) {
23153                final long token = Binder.clearCallingIdentity();
23154                try {
23155                    am.killProcessesBelowForeground("setPermissionEnforcement");
23156                } catch (RemoteException e) {
23157                } finally {
23158                    Binder.restoreCallingIdentity(token);
23159                }
23160            }
23161        } else {
23162            throw new IllegalArgumentException("No selective enforcement for " + permission);
23163        }
23164    }
23165
23166    @Override
23167    @Deprecated
23168    public boolean isPermissionEnforced(String permission) {
23169        // allow instant applications
23170        return true;
23171    }
23172
23173    @Override
23174    public boolean isStorageLow() {
23175        // allow instant applications
23176        final long token = Binder.clearCallingIdentity();
23177        try {
23178            final DeviceStorageMonitorInternal
23179                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
23180            if (dsm != null) {
23181                return dsm.isMemoryLow();
23182            } else {
23183                return false;
23184            }
23185        } finally {
23186            Binder.restoreCallingIdentity(token);
23187        }
23188    }
23189
23190    @Override
23191    public IPackageInstaller getPackageInstaller() {
23192        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23193            return null;
23194        }
23195        return mInstallerService;
23196    }
23197
23198    @Override
23199    public IArtManager getArtManager() {
23200        return mArtManagerService;
23201    }
23202
23203    private boolean userNeedsBadging(int userId) {
23204        int index = mUserNeedsBadging.indexOfKey(userId);
23205        if (index < 0) {
23206            final UserInfo userInfo;
23207            final long token = Binder.clearCallingIdentity();
23208            try {
23209                userInfo = sUserManager.getUserInfo(userId);
23210            } finally {
23211                Binder.restoreCallingIdentity(token);
23212            }
23213            final boolean b;
23214            if (userInfo != null && userInfo.isManagedProfile()) {
23215                b = true;
23216            } else {
23217                b = false;
23218            }
23219            mUserNeedsBadging.put(userId, b);
23220            return b;
23221        }
23222        return mUserNeedsBadging.valueAt(index);
23223    }
23224
23225    @Override
23226    public KeySet getKeySetByAlias(String packageName, String alias) {
23227        if (packageName == null || alias == null) {
23228            return null;
23229        }
23230        synchronized(mPackages) {
23231            final PackageParser.Package pkg = mPackages.get(packageName);
23232            if (pkg == null) {
23233                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23234                throw new IllegalArgumentException("Unknown package: " + packageName);
23235            }
23236            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23237            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
23238                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
23239                throw new IllegalArgumentException("Unknown package: " + packageName);
23240            }
23241            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23242            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
23243        }
23244    }
23245
23246    @Override
23247    public KeySet getSigningKeySet(String packageName) {
23248        if (packageName == null) {
23249            return null;
23250        }
23251        synchronized(mPackages) {
23252            final int callingUid = Binder.getCallingUid();
23253            final int callingUserId = UserHandle.getUserId(callingUid);
23254            final PackageParser.Package pkg = mPackages.get(packageName);
23255            if (pkg == null) {
23256                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23257                throw new IllegalArgumentException("Unknown package: " + packageName);
23258            }
23259            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23260            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
23261                // filter and pretend the package doesn't exist
23262                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
23263                        + ", uid:" + callingUid);
23264                throw new IllegalArgumentException("Unknown package: " + packageName);
23265            }
23266            if (pkg.applicationInfo.uid != callingUid
23267                    && Process.SYSTEM_UID != callingUid) {
23268                throw new SecurityException("May not access signing KeySet of other apps.");
23269            }
23270            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23271            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
23272        }
23273    }
23274
23275    @Override
23276    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
23277        final int callingUid = Binder.getCallingUid();
23278        if (getInstantAppPackageName(callingUid) != null) {
23279            return false;
23280        }
23281        if (packageName == null || ks == null) {
23282            return false;
23283        }
23284        synchronized(mPackages) {
23285            final PackageParser.Package pkg = mPackages.get(packageName);
23286            if (pkg == null
23287                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23288                            UserHandle.getUserId(callingUid))) {
23289                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23290                throw new IllegalArgumentException("Unknown package: " + packageName);
23291            }
23292            IBinder ksh = ks.getToken();
23293            if (ksh instanceof KeySetHandle) {
23294                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23295                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23296            }
23297            return false;
23298        }
23299    }
23300
23301    @Override
23302    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23303        final int callingUid = Binder.getCallingUid();
23304        if (getInstantAppPackageName(callingUid) != null) {
23305            return false;
23306        }
23307        if (packageName == null || ks == null) {
23308            return false;
23309        }
23310        synchronized(mPackages) {
23311            final PackageParser.Package pkg = mPackages.get(packageName);
23312            if (pkg == null
23313                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23314                            UserHandle.getUserId(callingUid))) {
23315                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23316                throw new IllegalArgumentException("Unknown package: " + packageName);
23317            }
23318            IBinder ksh = ks.getToken();
23319            if (ksh instanceof KeySetHandle) {
23320                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23321                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23322            }
23323            return false;
23324        }
23325    }
23326
23327    private void deletePackageIfUnusedLPr(final String packageName) {
23328        PackageSetting ps = mSettings.mPackages.get(packageName);
23329        if (ps == null) {
23330            return;
23331        }
23332        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23333            // TODO Implement atomic delete if package is unused
23334            // It is currently possible that the package will be deleted even if it is installed
23335            // after this method returns.
23336            mHandler.post(new Runnable() {
23337                public void run() {
23338                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23339                            0, PackageManager.DELETE_ALL_USERS);
23340                }
23341            });
23342        }
23343    }
23344
23345    /**
23346     * Check and throw if the given before/after packages would be considered a
23347     * downgrade.
23348     */
23349    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23350            throws PackageManagerException {
23351        if (after.getLongVersionCode() < before.getLongVersionCode()) {
23352            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23353                    "Update version code " + after.versionCode + " is older than current "
23354                    + before.getLongVersionCode());
23355        } else if (after.getLongVersionCode() == before.getLongVersionCode()) {
23356            if (after.baseRevisionCode < before.baseRevisionCode) {
23357                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23358                        "Update base revision code " + after.baseRevisionCode
23359                        + " is older than current " + before.baseRevisionCode);
23360            }
23361
23362            if (!ArrayUtils.isEmpty(after.splitNames)) {
23363                for (int i = 0; i < after.splitNames.length; i++) {
23364                    final String splitName = after.splitNames[i];
23365                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23366                    if (j != -1) {
23367                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23368                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23369                                    "Update split " + splitName + " revision code "
23370                                    + after.splitRevisionCodes[i] + " is older than current "
23371                                    + before.splitRevisionCodes[j]);
23372                        }
23373                    }
23374                }
23375            }
23376        }
23377    }
23378
23379    private static class MoveCallbacks extends Handler {
23380        private static final int MSG_CREATED = 1;
23381        private static final int MSG_STATUS_CHANGED = 2;
23382
23383        private final RemoteCallbackList<IPackageMoveObserver>
23384                mCallbacks = new RemoteCallbackList<>();
23385
23386        private final SparseIntArray mLastStatus = new SparseIntArray();
23387
23388        public MoveCallbacks(Looper looper) {
23389            super(looper);
23390        }
23391
23392        public void register(IPackageMoveObserver callback) {
23393            mCallbacks.register(callback);
23394        }
23395
23396        public void unregister(IPackageMoveObserver callback) {
23397            mCallbacks.unregister(callback);
23398        }
23399
23400        @Override
23401        public void handleMessage(Message msg) {
23402            final SomeArgs args = (SomeArgs) msg.obj;
23403            final int n = mCallbacks.beginBroadcast();
23404            for (int i = 0; i < n; i++) {
23405                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23406                try {
23407                    invokeCallback(callback, msg.what, args);
23408                } catch (RemoteException ignored) {
23409                }
23410            }
23411            mCallbacks.finishBroadcast();
23412            args.recycle();
23413        }
23414
23415        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23416                throws RemoteException {
23417            switch (what) {
23418                case MSG_CREATED: {
23419                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23420                    break;
23421                }
23422                case MSG_STATUS_CHANGED: {
23423                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23424                    break;
23425                }
23426            }
23427        }
23428
23429        private void notifyCreated(int moveId, Bundle extras) {
23430            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23431
23432            final SomeArgs args = SomeArgs.obtain();
23433            args.argi1 = moveId;
23434            args.arg2 = extras;
23435            obtainMessage(MSG_CREATED, args).sendToTarget();
23436        }
23437
23438        private void notifyStatusChanged(int moveId, int status) {
23439            notifyStatusChanged(moveId, status, -1);
23440        }
23441
23442        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23443            Slog.v(TAG, "Move " + moveId + " status " + status);
23444
23445            final SomeArgs args = SomeArgs.obtain();
23446            args.argi1 = moveId;
23447            args.argi2 = status;
23448            args.arg3 = estMillis;
23449            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23450
23451            synchronized (mLastStatus) {
23452                mLastStatus.put(moveId, status);
23453            }
23454        }
23455    }
23456
23457    private final static class OnPermissionChangeListeners extends Handler {
23458        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23459
23460        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23461                new RemoteCallbackList<>();
23462
23463        public OnPermissionChangeListeners(Looper looper) {
23464            super(looper);
23465        }
23466
23467        @Override
23468        public void handleMessage(Message msg) {
23469            switch (msg.what) {
23470                case MSG_ON_PERMISSIONS_CHANGED: {
23471                    final int uid = msg.arg1;
23472                    handleOnPermissionsChanged(uid);
23473                } break;
23474            }
23475        }
23476
23477        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23478            mPermissionListeners.register(listener);
23479
23480        }
23481
23482        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23483            mPermissionListeners.unregister(listener);
23484        }
23485
23486        public void onPermissionsChanged(int uid) {
23487            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23488                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23489            }
23490        }
23491
23492        private void handleOnPermissionsChanged(int uid) {
23493            final int count = mPermissionListeners.beginBroadcast();
23494            try {
23495                for (int i = 0; i < count; i++) {
23496                    IOnPermissionsChangeListener callback = mPermissionListeners
23497                            .getBroadcastItem(i);
23498                    try {
23499                        callback.onPermissionsChanged(uid);
23500                    } catch (RemoteException e) {
23501                        Log.e(TAG, "Permission listener is dead", e);
23502                    }
23503                }
23504            } finally {
23505                mPermissionListeners.finishBroadcast();
23506            }
23507        }
23508    }
23509
23510    private class PackageManagerNative extends IPackageManagerNative.Stub {
23511        @Override
23512        public String[] getNamesForUids(int[] uids) throws RemoteException {
23513            final String[] results = PackageManagerService.this.getNamesForUids(uids);
23514            // massage results so they can be parsed by the native binder
23515            for (int i = results.length - 1; i >= 0; --i) {
23516                if (results[i] == null) {
23517                    results[i] = "";
23518                }
23519            }
23520            return results;
23521        }
23522
23523        // NB: this differentiates between preloads and sideloads
23524        @Override
23525        public String getInstallerForPackage(String packageName) throws RemoteException {
23526            final String installerName = getInstallerPackageName(packageName);
23527            if (!TextUtils.isEmpty(installerName)) {
23528                return installerName;
23529            }
23530            // differentiate between preload and sideload
23531            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23532            ApplicationInfo appInfo = getApplicationInfo(packageName,
23533                                    /*flags*/ 0,
23534                                    /*userId*/ callingUser);
23535            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23536                return "preload";
23537            }
23538            return "";
23539        }
23540
23541        @Override
23542        public long getVersionCodeForPackage(String packageName) throws RemoteException {
23543            try {
23544                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23545                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
23546                if (pInfo != null) {
23547                    return pInfo.getLongVersionCode();
23548                }
23549            } catch (Exception e) {
23550            }
23551            return 0;
23552        }
23553    }
23554
23555    private class PackageManagerInternalImpl extends PackageManagerInternal {
23556        @Override
23557        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
23558                int flagValues, int userId) {
23559            PackageManagerService.this.updatePermissionFlags(
23560                    permName, packageName, flagMask, flagValues, userId);
23561        }
23562
23563        @Override
23564        public boolean isDataRestoreSafe(byte[] restoringFromSigHash, String packageName) {
23565            SigningDetails sd = getSigningDetails(packageName);
23566            if (sd == null) {
23567                return false;
23568            }
23569            return sd.hasSha256Certificate(restoringFromSigHash,
23570                    SigningDetails.CertCapabilities.INSTALLED_DATA);
23571        }
23572
23573        @Override
23574        public boolean isDataRestoreSafe(Signature restoringFromSig, String packageName) {
23575            SigningDetails sd = getSigningDetails(packageName);
23576            if (sd == null) {
23577                return false;
23578            }
23579            return sd.hasCertificate(restoringFromSig,
23580                    SigningDetails.CertCapabilities.INSTALLED_DATA);
23581        }
23582
23583        private SigningDetails getSigningDetails(@NonNull String packageName) {
23584            synchronized (mPackages) {
23585                PackageParser.Package p = mPackages.get(packageName);
23586                if (p == null) {
23587                    return null;
23588                }
23589                return p.mSigningDetails;
23590            }
23591        }
23592
23593        @Override
23594        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
23595            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
23596        }
23597
23598        @Override
23599        public boolean isInstantApp(String packageName, int userId) {
23600            return PackageManagerService.this.isInstantApp(packageName, userId);
23601        }
23602
23603        @Override
23604        public String getInstantAppPackageName(int uid) {
23605            return PackageManagerService.this.getInstantAppPackageName(uid);
23606        }
23607
23608        @Override
23609        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
23610            synchronized (mPackages) {
23611                return PackageManagerService.this.filterAppAccessLPr(
23612                        (PackageSetting) pkg.mExtras, callingUid, userId);
23613            }
23614        }
23615
23616        @Override
23617        public PackageParser.Package getPackage(String packageName) {
23618            synchronized (mPackages) {
23619                packageName = resolveInternalPackageNameLPr(
23620                        packageName, PackageManager.VERSION_CODE_HIGHEST);
23621                return mPackages.get(packageName);
23622            }
23623        }
23624
23625        @Override
23626        public PackageList getPackageList(PackageListObserver observer) {
23627            synchronized (mPackages) {
23628                final int N = mPackages.size();
23629                final ArrayList<String> list = new ArrayList<>(N);
23630                for (int i = 0; i < N; i++) {
23631                    list.add(mPackages.keyAt(i));
23632                }
23633                final PackageList packageList = new PackageList(list, observer);
23634                if (observer != null) {
23635                    mPackageListObservers.add(packageList);
23636                }
23637                return packageList;
23638            }
23639        }
23640
23641        @Override
23642        public void removePackageListObserver(PackageListObserver observer) {
23643            synchronized (mPackages) {
23644                mPackageListObservers.remove(observer);
23645            }
23646        }
23647
23648        @Override
23649        public PackageParser.Package getDisabledPackage(String packageName) {
23650            synchronized (mPackages) {
23651                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
23652                return (ps != null) ? ps.pkg : null;
23653            }
23654        }
23655
23656        @Override
23657        public String getKnownPackageName(int knownPackage, int userId) {
23658            switch(knownPackage) {
23659                case PackageManagerInternal.PACKAGE_BROWSER:
23660                    return getDefaultBrowserPackageName(userId);
23661                case PackageManagerInternal.PACKAGE_INSTALLER:
23662                    return mRequiredInstallerPackage;
23663                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
23664                    return mSetupWizardPackage;
23665                case PackageManagerInternal.PACKAGE_SYSTEM:
23666                    return "android";
23667                case PackageManagerInternal.PACKAGE_VERIFIER:
23668                    return mRequiredVerifierPackage;
23669                case PackageManagerInternal.PACKAGE_SYSTEM_TEXT_CLASSIFIER:
23670                    return mSystemTextClassifierPackage;
23671            }
23672            return null;
23673        }
23674
23675        @Override
23676        public boolean isResolveActivityComponent(ComponentInfo component) {
23677            return mResolveActivity.packageName.equals(component.packageName)
23678                    && mResolveActivity.name.equals(component.name);
23679        }
23680
23681        @Override
23682        public void setLocationPackagesProvider(PackagesProvider provider) {
23683            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
23684        }
23685
23686        @Override
23687        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23688            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
23689        }
23690
23691        @Override
23692        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23693            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
23694        }
23695
23696        @Override
23697        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23698            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
23699        }
23700
23701        @Override
23702        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23703            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
23704        }
23705
23706        @Override
23707        public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) {
23708            mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider);
23709        }
23710
23711        @Override
23712        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23713            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
23714        }
23715
23716        @Override
23717        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23718            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
23719        }
23720
23721        @Override
23722        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23723            synchronized (mPackages) {
23724                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23725            }
23726            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
23727        }
23728
23729        @Override
23730        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23731            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
23732                    packageName, userId);
23733        }
23734
23735        @Override
23736        public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) {
23737            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp(
23738                    packageName, userId);
23739        }
23740
23741        @Override
23742        public void setKeepUninstalledPackages(final List<String> packageList) {
23743            Preconditions.checkNotNull(packageList);
23744            List<String> removedFromList = null;
23745            synchronized (mPackages) {
23746                if (mKeepUninstalledPackages != null) {
23747                    final int packagesCount = mKeepUninstalledPackages.size();
23748                    for (int i = 0; i < packagesCount; i++) {
23749                        String oldPackage = mKeepUninstalledPackages.get(i);
23750                        if (packageList != null && packageList.contains(oldPackage)) {
23751                            continue;
23752                        }
23753                        if (removedFromList == null) {
23754                            removedFromList = new ArrayList<>();
23755                        }
23756                        removedFromList.add(oldPackage);
23757                    }
23758                }
23759                mKeepUninstalledPackages = new ArrayList<>(packageList);
23760                if (removedFromList != null) {
23761                    final int removedCount = removedFromList.size();
23762                    for (int i = 0; i < removedCount; i++) {
23763                        deletePackageIfUnusedLPr(removedFromList.get(i));
23764                    }
23765                }
23766            }
23767        }
23768
23769        @Override
23770        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23771            synchronized (mPackages) {
23772                return mPermissionManager.isPermissionsReviewRequired(
23773                        mPackages.get(packageName), userId);
23774            }
23775        }
23776
23777        @Override
23778        public PackageInfo getPackageInfo(
23779                String packageName, int flags, int filterCallingUid, int userId) {
23780            return PackageManagerService.this
23781                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
23782                            flags, filterCallingUid, userId);
23783        }
23784
23785        @Override
23786        public Bundle getSuspendedPackageLauncherExtras(String packageName, int userId) {
23787            synchronized (mPackages) {
23788                final PackageSetting ps = mSettings.mPackages.get(packageName);
23789                PersistableBundle launcherExtras = null;
23790                if (ps != null) {
23791                    launcherExtras = ps.readUserState(userId).suspendedLauncherExtras;
23792                }
23793                return (launcherExtras != null) ? new Bundle(launcherExtras.deepCopy()) : null;
23794            }
23795        }
23796
23797        @Override
23798        public int getPackageUid(String packageName, int flags, int userId) {
23799            return PackageManagerService.this
23800                    .getPackageUid(packageName, flags, userId);
23801        }
23802
23803        @Override
23804        public ApplicationInfo getApplicationInfo(
23805                String packageName, int flags, int filterCallingUid, int userId) {
23806            return PackageManagerService.this
23807                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
23808        }
23809
23810        @Override
23811        public ActivityInfo getActivityInfo(
23812                ComponentName component, int flags, int filterCallingUid, int userId) {
23813            return PackageManagerService.this
23814                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
23815        }
23816
23817        @Override
23818        public List<ResolveInfo> queryIntentActivities(
23819                Intent intent, int flags, int filterCallingUid, int userId) {
23820            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23821            return PackageManagerService.this
23822                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
23823                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
23824        }
23825
23826        @Override
23827        public List<ResolveInfo> queryIntentServices(
23828                Intent intent, int flags, int callingUid, int userId) {
23829            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23830            return PackageManagerService.this
23831                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
23832                            false);
23833        }
23834
23835        @Override
23836        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23837                int userId) {
23838            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23839        }
23840
23841        @Override
23842        public ComponentName getDefaultHomeActivity(int userId) {
23843            return PackageManagerService.this.getDefaultHomeActivity(userId);
23844        }
23845
23846        @Override
23847        public void setDeviceAndProfileOwnerPackages(
23848                int deviceOwnerUserId, String deviceOwnerPackage,
23849                SparseArray<String> profileOwnerPackages) {
23850            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23851                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23852        }
23853
23854        @Override
23855        public boolean isPackageDataProtected(int userId, String packageName) {
23856            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23857        }
23858
23859        @Override
23860        public boolean isPackageEphemeral(int userId, String packageName) {
23861            synchronized (mPackages) {
23862                final PackageSetting ps = mSettings.mPackages.get(packageName);
23863                return ps != null ? ps.getInstantApp(userId) : false;
23864            }
23865        }
23866
23867        @Override
23868        public boolean wasPackageEverLaunched(String packageName, int userId) {
23869            synchronized (mPackages) {
23870                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23871            }
23872        }
23873
23874        @Override
23875        public void grantRuntimePermission(String packageName, String permName, int userId,
23876                boolean overridePolicy) {
23877            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
23878                    permName, packageName, overridePolicy, getCallingUid(), userId,
23879                    mPermissionCallback);
23880        }
23881
23882        @Override
23883        public void revokeRuntimePermission(String packageName, String permName, int userId,
23884                boolean overridePolicy) {
23885            mPermissionManager.revokeRuntimePermission(
23886                    permName, packageName, overridePolicy, getCallingUid(), userId,
23887                    mPermissionCallback);
23888        }
23889
23890        @Override
23891        public String getNameForUid(int uid) {
23892            return PackageManagerService.this.getNameForUid(uid);
23893        }
23894
23895        @Override
23896        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23897                Intent origIntent, String resolvedType, String callingPackage,
23898                Bundle verificationBundle, int userId) {
23899            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23900                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
23901                    userId);
23902        }
23903
23904        @Override
23905        public void grantEphemeralAccess(int userId, Intent intent,
23906                int targetAppId, int ephemeralAppId) {
23907            synchronized (mPackages) {
23908                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23909                        targetAppId, ephemeralAppId);
23910            }
23911        }
23912
23913        @Override
23914        public boolean isInstantAppInstallerComponent(ComponentName component) {
23915            synchronized (mPackages) {
23916                return mInstantAppInstallerActivity != null
23917                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23918            }
23919        }
23920
23921        @Override
23922        public void pruneInstantApps() {
23923            mInstantAppRegistry.pruneInstantApps();
23924        }
23925
23926        @Override
23927        public String getSetupWizardPackageName() {
23928            return mSetupWizardPackage;
23929        }
23930
23931        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23932            if (policy != null) {
23933                mExternalSourcesPolicy = policy;
23934            }
23935        }
23936
23937        @Override
23938        public boolean isPackagePersistent(String packageName) {
23939            synchronized (mPackages) {
23940                PackageParser.Package pkg = mPackages.get(packageName);
23941                return pkg != null
23942                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23943                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23944                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23945                        : false;
23946            }
23947        }
23948
23949        @Override
23950        public boolean isLegacySystemApp(Package pkg) {
23951            synchronized (mPackages) {
23952                final PackageSetting ps = (PackageSetting) pkg.mExtras;
23953                return mPromoteSystemApps
23954                        && ps.isSystem()
23955                        && mExistingSystemPackages.contains(ps.name);
23956            }
23957        }
23958
23959        @Override
23960        public List<PackageInfo> getOverlayPackages(int userId) {
23961            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23962            synchronized (mPackages) {
23963                for (PackageParser.Package p : mPackages.values()) {
23964                    if (p.mOverlayTarget != null) {
23965                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23966                        if (pkg != null) {
23967                            overlayPackages.add(pkg);
23968                        }
23969                    }
23970                }
23971            }
23972            return overlayPackages;
23973        }
23974
23975        @Override
23976        public List<String> getTargetPackageNames(int userId) {
23977            List<String> targetPackages = new ArrayList<>();
23978            synchronized (mPackages) {
23979                for (PackageParser.Package p : mPackages.values()) {
23980                    if (p.mOverlayTarget == null) {
23981                        targetPackages.add(p.packageName);
23982                    }
23983                }
23984            }
23985            return targetPackages;
23986        }
23987
23988        @Override
23989        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23990                @Nullable List<String> overlayPackageNames) {
23991            synchronized (mPackages) {
23992                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23993                    Slog.e(TAG, "failed to find package " + targetPackageName);
23994                    return false;
23995                }
23996                ArrayList<String> overlayPaths = null;
23997                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
23998                    final int N = overlayPackageNames.size();
23999                    overlayPaths = new ArrayList<>(N);
24000                    for (int i = 0; i < N; i++) {
24001                        final String packageName = overlayPackageNames.get(i);
24002                        final PackageParser.Package pkg = mPackages.get(packageName);
24003                        if (pkg == null) {
24004                            Slog.e(TAG, "failed to find package " + packageName);
24005                            return false;
24006                        }
24007                        overlayPaths.add(pkg.baseCodePath);
24008                    }
24009                }
24010
24011                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
24012                ps.setOverlayPaths(overlayPaths, userId);
24013                return true;
24014            }
24015        }
24016
24017        @Override
24018        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24019                int flags, int userId, boolean resolveForStart) {
24020            return resolveIntentInternal(
24021                    intent, resolvedType, flags, userId, resolveForStart);
24022        }
24023
24024        @Override
24025        public ResolveInfo resolveService(Intent intent, String resolvedType,
24026                int flags, int userId, int callingUid) {
24027            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24028        }
24029
24030        @Override
24031        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
24032            return PackageManagerService.this.resolveContentProviderInternal(
24033                    name, flags, userId);
24034        }
24035
24036        @Override
24037        public void addIsolatedUid(int isolatedUid, int ownerUid) {
24038            synchronized (mPackages) {
24039                mIsolatedOwners.put(isolatedUid, ownerUid);
24040            }
24041        }
24042
24043        @Override
24044        public void removeIsolatedUid(int isolatedUid) {
24045            synchronized (mPackages) {
24046                mIsolatedOwners.delete(isolatedUid);
24047            }
24048        }
24049
24050        @Override
24051        public int getUidTargetSdkVersion(int uid) {
24052            synchronized (mPackages) {
24053                return getUidTargetSdkVersionLockedLPr(uid);
24054            }
24055        }
24056
24057        @Override
24058        public int getPackageTargetSdkVersion(String packageName) {
24059            synchronized (mPackages) {
24060                return getPackageTargetSdkVersionLockedLPr(packageName);
24061            }
24062        }
24063
24064        @Override
24065        public boolean canAccessInstantApps(int callingUid, int userId) {
24066            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24067        }
24068
24069        @Override
24070        public boolean canAccessComponent(int callingUid, ComponentName component, int userId) {
24071            synchronized (mPackages) {
24072                final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
24073                return !PackageManagerService.this.filterAppAccessLPr(
24074                        ps, callingUid, component, TYPE_UNKNOWN, userId);
24075            }
24076        }
24077
24078        @Override
24079        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
24080            synchronized (mPackages) {
24081                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
24082            }
24083        }
24084
24085        @Override
24086        public void notifyPackageUse(String packageName, int reason) {
24087            synchronized (mPackages) {
24088                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
24089            }
24090        }
24091    }
24092
24093    @Override
24094    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24095        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24096        synchronized (mPackages) {
24097            final long identity = Binder.clearCallingIdentity();
24098            try {
24099                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
24100                        packageNames, userId);
24101            } finally {
24102                Binder.restoreCallingIdentity(identity);
24103            }
24104        }
24105    }
24106
24107    @Override
24108    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24109        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24110        synchronized (mPackages) {
24111            final long identity = Binder.clearCallingIdentity();
24112            try {
24113                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
24114                        packageNames, userId);
24115            } finally {
24116                Binder.restoreCallingIdentity(identity);
24117            }
24118        }
24119    }
24120
24121    @Override
24122    public void grantDefaultPermissionsToEnabledTelephonyDataServices(
24123            String[] packageNames, int userId) {
24124        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledTelephonyDataServices");
24125        synchronized (mPackages) {
24126            Binder.withCleanCallingIdentity( () -> {
24127                mDefaultPermissionPolicy.
24128                        grantDefaultPermissionsToEnabledTelephonyDataServices(
24129                                packageNames, userId);
24130            });
24131        }
24132    }
24133
24134    @Override
24135    public void revokeDefaultPermissionsFromDisabledTelephonyDataServices(
24136            String[] packageNames, int userId) {
24137        enforceSystemOrPhoneCaller("revokeDefaultPermissionsFromDisabledTelephonyDataServices");
24138        synchronized (mPackages) {
24139            Binder.withCleanCallingIdentity( () -> {
24140                mDefaultPermissionPolicy.
24141                        revokeDefaultPermissionsFromDisabledTelephonyDataServices(
24142                                packageNames, userId);
24143            });
24144        }
24145    }
24146
24147    @Override
24148    public void grantDefaultPermissionsToActiveLuiApp(String packageName, int userId) {
24149        enforceSystemOrPhoneCaller("grantDefaultPermissionsToActiveLuiApp");
24150        synchronized (mPackages) {
24151            final long identity = Binder.clearCallingIdentity();
24152            try {
24153                mDefaultPermissionPolicy.grantDefaultPermissionsToActiveLuiApp(
24154                        packageName, userId);
24155            } finally {
24156                Binder.restoreCallingIdentity(identity);
24157            }
24158        }
24159    }
24160
24161    @Override
24162    public void revokeDefaultPermissionsFromLuiApps(String[] packageNames, int userId) {
24163        enforceSystemOrPhoneCaller("revokeDefaultPermissionsFromLuiApps");
24164        synchronized (mPackages) {
24165            final long identity = Binder.clearCallingIdentity();
24166            try {
24167                mDefaultPermissionPolicy.revokeDefaultPermissionsFromLuiApps(packageNames, userId);
24168            } finally {
24169                Binder.restoreCallingIdentity(identity);
24170            }
24171        }
24172    }
24173
24174    private static void enforceSystemOrPhoneCaller(String tag) {
24175        int callingUid = Binder.getCallingUid();
24176        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24177            throw new SecurityException(
24178                    "Cannot call " + tag + " from UID " + callingUid);
24179        }
24180    }
24181
24182    boolean isHistoricalPackageUsageAvailable() {
24183        return mPackageUsage.isHistoricalPackageUsageAvailable();
24184    }
24185
24186    /**
24187     * Return a <b>copy</b> of the collection of packages known to the package manager.
24188     * @return A copy of the values of mPackages.
24189     */
24190    Collection<PackageParser.Package> getPackages() {
24191        synchronized (mPackages) {
24192            return new ArrayList<>(mPackages.values());
24193        }
24194    }
24195
24196    /**
24197     * Logs process start information (including base APK hash) to the security log.
24198     * @hide
24199     */
24200    @Override
24201    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24202            String apkFile, int pid) {
24203        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24204            return;
24205        }
24206        if (!SecurityLog.isLoggingEnabled()) {
24207            return;
24208        }
24209        Bundle data = new Bundle();
24210        data.putLong("startTimestamp", System.currentTimeMillis());
24211        data.putString("processName", processName);
24212        data.putInt("uid", uid);
24213        data.putString("seinfo", seinfo);
24214        data.putString("apkFile", apkFile);
24215        data.putInt("pid", pid);
24216        Message msg = mProcessLoggingHandler.obtainMessage(
24217                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24218        msg.setData(data);
24219        mProcessLoggingHandler.sendMessage(msg);
24220    }
24221
24222    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24223        return mCompilerStats.getPackageStats(pkgName);
24224    }
24225
24226    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24227        return getOrCreateCompilerPackageStats(pkg.packageName);
24228    }
24229
24230    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24231        return mCompilerStats.getOrCreatePackageStats(pkgName);
24232    }
24233
24234    public void deleteCompilerPackageStats(String pkgName) {
24235        mCompilerStats.deletePackageStats(pkgName);
24236    }
24237
24238    @Override
24239    public int getInstallReason(String packageName, int userId) {
24240        final int callingUid = Binder.getCallingUid();
24241        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24242                true /* requireFullPermission */, false /* checkShell */,
24243                "get install reason");
24244        synchronized (mPackages) {
24245            final PackageSetting ps = mSettings.mPackages.get(packageName);
24246            if (filterAppAccessLPr(ps, callingUid, userId)) {
24247                return PackageManager.INSTALL_REASON_UNKNOWN;
24248            }
24249            if (ps != null) {
24250                return ps.getInstallReason(userId);
24251            }
24252        }
24253        return PackageManager.INSTALL_REASON_UNKNOWN;
24254    }
24255
24256    @Override
24257    public boolean canRequestPackageInstalls(String packageName, int userId) {
24258        return canRequestPackageInstallsInternal(packageName, 0, userId,
24259                true /* throwIfPermNotDeclared*/);
24260    }
24261
24262    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24263            boolean throwIfPermNotDeclared) {
24264        int callingUid = Binder.getCallingUid();
24265        int uid = getPackageUid(packageName, 0, userId);
24266        if (callingUid != uid && callingUid != Process.ROOT_UID
24267                && callingUid != Process.SYSTEM_UID) {
24268            throw new SecurityException(
24269                    "Caller uid " + callingUid + " does not own package " + packageName);
24270        }
24271        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24272        if (info == null) {
24273            return false;
24274        }
24275        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24276            return false;
24277        }
24278        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24279        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24280        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24281            if (throwIfPermNotDeclared) {
24282                throw new SecurityException("Need to declare " + appOpPermission
24283                        + " to call this api");
24284            } else {
24285                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24286                return false;
24287            }
24288        }
24289        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24290            return false;
24291        }
24292        if (mExternalSourcesPolicy != null) {
24293            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24294            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24295                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24296            }
24297        }
24298        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24299    }
24300
24301    @Override
24302    public ComponentName getInstantAppResolverSettingsComponent() {
24303        return mInstantAppResolverSettingsComponent;
24304    }
24305
24306    @Override
24307    public ComponentName getInstantAppInstallerComponent() {
24308        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24309            return null;
24310        }
24311        return mInstantAppInstallerActivity == null
24312                ? null : mInstantAppInstallerActivity.getComponentName();
24313    }
24314
24315    @Override
24316    public String getInstantAppAndroidId(String packageName, int userId) {
24317        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24318                "getInstantAppAndroidId");
24319        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
24320                true /* requireFullPermission */, false /* checkShell */,
24321                "getInstantAppAndroidId");
24322        // Make sure the target is an Instant App.
24323        if (!isInstantApp(packageName, userId)) {
24324            return null;
24325        }
24326        synchronized (mPackages) {
24327            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24328        }
24329    }
24330
24331    boolean canHaveOatDir(String packageName) {
24332        synchronized (mPackages) {
24333            PackageParser.Package p = mPackages.get(packageName);
24334            if (p == null) {
24335                return false;
24336            }
24337            return p.canHaveOatDir();
24338        }
24339    }
24340
24341    private String getOatDir(PackageParser.Package pkg) {
24342        if (!pkg.canHaveOatDir()) {
24343            return null;
24344        }
24345        File codePath = new File(pkg.codePath);
24346        if (codePath.isDirectory()) {
24347            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
24348        }
24349        return null;
24350    }
24351
24352    void deleteOatArtifactsOfPackage(String packageName) {
24353        final String[] instructionSets;
24354        final List<String> codePaths;
24355        final String oatDir;
24356        final PackageParser.Package pkg;
24357        synchronized (mPackages) {
24358            pkg = mPackages.get(packageName);
24359        }
24360        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
24361        codePaths = pkg.getAllCodePaths();
24362        oatDir = getOatDir(pkg);
24363
24364        for (String codePath : codePaths) {
24365            for (String isa : instructionSets) {
24366                try {
24367                    mInstaller.deleteOdex(codePath, isa, oatDir);
24368                } catch (InstallerException e) {
24369                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
24370                }
24371            }
24372        }
24373    }
24374
24375    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
24376        Set<String> unusedPackages = new HashSet<>();
24377        long currentTimeInMillis = System.currentTimeMillis();
24378        synchronized (mPackages) {
24379            for (PackageParser.Package pkg : mPackages.values()) {
24380                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
24381                if (ps == null) {
24382                    continue;
24383                }
24384                PackageDexUsage.PackageUseInfo packageUseInfo =
24385                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
24386                if (PackageManagerServiceUtils
24387                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
24388                                downgradeTimeThresholdMillis, packageUseInfo,
24389                                pkg.getLatestPackageUseTimeInMills(),
24390                                pkg.getLatestForegroundPackageUseTimeInMills())) {
24391                    unusedPackages.add(pkg.packageName);
24392                }
24393            }
24394        }
24395        return unusedPackages;
24396    }
24397
24398    @Override
24399    public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning,
24400            int userId) {
24401        final int callingUid = Binder.getCallingUid();
24402        final int callingAppId = UserHandle.getAppId(callingUid);
24403
24404        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24405                true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo");
24406
24407        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24408                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24409            throw new SecurityException("Caller must have the "
24410                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24411        }
24412
24413        synchronized(mPackages) {
24414            mSettings.setHarmfulAppWarningLPw(packageName, warning, userId);
24415            scheduleWritePackageRestrictionsLocked(userId);
24416        }
24417    }
24418
24419    @Nullable
24420    @Override
24421    public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) {
24422        final int callingUid = Binder.getCallingUid();
24423        final int callingAppId = UserHandle.getAppId(callingUid);
24424
24425        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24426                true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo");
24427
24428        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24429                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24430            throw new SecurityException("Caller must have the "
24431                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24432        }
24433
24434        synchronized(mPackages) {
24435            return mSettings.getHarmfulAppWarningLPr(packageName, userId);
24436        }
24437    }
24438
24439    @Override
24440    public boolean isPackageStateProtected(@NonNull String packageName, @UserIdInt int userId) {
24441        final int callingUid = Binder.getCallingUid();
24442        final int callingAppId = UserHandle.getAppId(callingUid);
24443
24444        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24445                false /*requireFullPermission*/, true /*checkShell*/, "isPackageStateProtected");
24446
24447        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID
24448                && checkUidPermission(MANAGE_DEVICE_ADMINS, callingUid) != PERMISSION_GRANTED) {
24449            throw new SecurityException("Caller must have the "
24450                    + MANAGE_DEVICE_ADMINS + " permission.");
24451        }
24452
24453        return mProtectedPackages.isPackageStateProtected(userId, packageName);
24454    }
24455}
24456
24457interface PackageSender {
24458    /**
24459     * @param userIds User IDs where the action occurred on a full application
24460     * @param instantUserIds User IDs where the action occurred on an instant application
24461     */
24462    void sendPackageBroadcast(final String action, final String pkg,
24463        final Bundle extras, final int flags, final String targetPkg,
24464        final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds);
24465    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
24466        boolean includeStopped, int appId, int[] userIds, int[] instantUserIds);
24467    void notifyPackageAdded(String packageName);
24468    void notifyPackageRemoved(String packageName);
24469}
24470