PackageManagerService.java revision 2fd43ba63ef336f9e0edc9c742b85507c46b3bc9
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.SET_HARMFUL_APP_WARNINGS;
21import static android.Manifest.permission.INSTALL_PACKAGES;
22import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS;
23import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
24import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
25import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
26import static android.content.pm.PackageManager.CERT_INPUT_RAW_X509;
27import static android.content.pm.PackageManager.CERT_INPUT_SHA256;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
31import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
32import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
33import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
39import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
40import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
41import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
42import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
43import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
44import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
45import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
49import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
50import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
51import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
52import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
53import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
54import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
55import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
56import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
57import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
58import static android.content.pm.PackageManager.INSTALL_INTERNAL;
59import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
65import static android.content.pm.PackageManager.MATCH_ALL;
66import static android.content.pm.PackageManager.MATCH_ANY_USER;
67import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
68import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
70import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
71import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
72import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
73import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
74import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
75import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
76import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
77import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
78import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
79import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER;
80import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
81import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
82import static android.content.pm.PackageManager.PERMISSION_DENIED;
83import static android.content.pm.PackageManager.PERMISSION_GRANTED;
84import static android.content.pm.PackageParser.isApkFile;
85import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
86import static android.os.storage.StorageManager.FLAG_STORAGE_CE;
87import static android.os.storage.StorageManager.FLAG_STORAGE_DE;
88import static android.system.OsConstants.O_CREAT;
89import static android.system.OsConstants.O_RDWR;
90import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
91import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
92import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
93import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
94import static com.android.internal.util.ArrayUtils.appendElement;
95import static com.android.internal.util.ArrayUtils.appendInt;
96import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
97import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
98import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
99import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
100import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
102import static com.android.server.pm.PackageManagerServiceUtils.compareSignatures;
103import static com.android.server.pm.PackageManagerServiceUtils.compressedFileExists;
104import static com.android.server.pm.PackageManagerServiceUtils.decompressFile;
105import static com.android.server.pm.PackageManagerServiceUtils.deriveAbiOverride;
106import static com.android.server.pm.PackageManagerServiceUtils.dumpCriticalInfo;
107import static com.android.server.pm.PackageManagerServiceUtils.getCompressedFiles;
108import static com.android.server.pm.PackageManagerServiceUtils.getLastModifiedTime;
109import static com.android.server.pm.PackageManagerServiceUtils.logCriticalInfo;
110import static com.android.server.pm.PackageManagerServiceUtils.verifySignatures;
111import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_FAILURE;
112import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS;
113import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
114
115import android.Manifest;
116import android.annotation.IntDef;
117import android.annotation.NonNull;
118import android.annotation.Nullable;
119import android.app.ActivityManager;
120import android.app.ActivityManagerInternal;
121import android.app.AppOpsManager;
122import android.app.IActivityManager;
123import android.app.ResourcesManager;
124import android.app.admin.IDevicePolicyManager;
125import android.app.admin.SecurityLog;
126import android.app.backup.IBackupManager;
127import android.content.BroadcastReceiver;
128import android.content.ComponentName;
129import android.content.ContentResolver;
130import android.content.Context;
131import android.content.IIntentReceiver;
132import android.content.Intent;
133import android.content.IntentFilter;
134import android.content.IntentSender;
135import android.content.IntentSender.SendIntentException;
136import android.content.ServiceConnection;
137import android.content.pm.ActivityInfo;
138import android.content.pm.ApplicationInfo;
139import android.content.pm.AppsQueryHelper;
140import android.content.pm.AuxiliaryResolveInfo;
141import android.content.pm.ChangedPackages;
142import android.content.pm.ComponentInfo;
143import android.content.pm.FallbackCategoryProvider;
144import android.content.pm.FeatureInfo;
145import android.content.pm.IDexModuleRegisterCallback;
146import android.content.pm.IOnPermissionsChangeListener;
147import android.content.pm.IPackageDataObserver;
148import android.content.pm.IPackageDeleteObserver;
149import android.content.pm.IPackageDeleteObserver2;
150import android.content.pm.IPackageInstallObserver2;
151import android.content.pm.IPackageInstaller;
152import android.content.pm.IPackageManager;
153import android.content.pm.IPackageManagerNative;
154import android.content.pm.IPackageMoveObserver;
155import android.content.pm.IPackageStatsObserver;
156import android.content.pm.InstantAppInfo;
157import android.content.pm.InstantAppRequest;
158import android.content.pm.InstantAppResolveInfo;
159import android.content.pm.InstrumentationInfo;
160import android.content.pm.IntentFilterVerificationInfo;
161import android.content.pm.KeySet;
162import android.content.pm.PackageCleanItem;
163import android.content.pm.PackageInfo;
164import android.content.pm.PackageInfoLite;
165import android.content.pm.PackageInstaller;
166import android.content.pm.PackageList;
167import android.content.pm.PackageManager;
168import android.content.pm.PackageManagerInternal;
169import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
170import android.content.pm.PackageManagerInternal.PackageListObserver;
171import android.content.pm.PackageParser;
172import android.content.pm.PackageParser.ActivityIntentInfo;
173import android.content.pm.PackageParser.Package;
174import android.content.pm.PackageParser.PackageLite;
175import android.content.pm.PackageParser.PackageParserException;
176import android.content.pm.PackageParser.ParseFlags;
177import android.content.pm.PackageParser.ServiceIntentInfo;
178import android.content.pm.PackageParser.SigningDetails;
179import android.content.pm.PackageParser.SigningDetails.SignatureSchemeVersion;
180import android.content.pm.PackageStats;
181import android.content.pm.PackageUserState;
182import android.content.pm.ParceledListSlice;
183import android.content.pm.PermissionGroupInfo;
184import android.content.pm.PermissionInfo;
185import android.content.pm.ProviderInfo;
186import android.content.pm.ResolveInfo;
187import android.content.pm.ServiceInfo;
188import android.content.pm.SharedLibraryInfo;
189import android.content.pm.Signature;
190import android.content.pm.UserInfo;
191import android.content.pm.VerifierDeviceIdentity;
192import android.content.pm.VerifierInfo;
193import android.content.pm.VersionedPackage;
194import android.content.pm.dex.ArtManager;
195import android.content.pm.dex.DexMetadataHelper;
196import android.content.pm.dex.IArtManager;
197import android.content.res.Resources;
198import android.database.ContentObserver;
199import android.graphics.Bitmap;
200import android.hardware.display.DisplayManager;
201import android.net.Uri;
202import android.os.Binder;
203import android.os.Build;
204import android.os.Bundle;
205import android.os.Debug;
206import android.os.Environment;
207import android.os.Environment.UserEnvironment;
208import android.os.FileUtils;
209import android.os.Handler;
210import android.os.IBinder;
211import android.os.Looper;
212import android.os.Message;
213import android.os.Parcel;
214import android.os.ParcelFileDescriptor;
215import android.os.PatternMatcher;
216import android.os.PersistableBundle;
217import android.os.Process;
218import android.os.RemoteCallbackList;
219import android.os.RemoteException;
220import android.os.ResultReceiver;
221import android.os.SELinux;
222import android.os.ServiceManager;
223import android.os.ShellCallback;
224import android.os.SystemClock;
225import android.os.SystemProperties;
226import android.os.Trace;
227import android.os.UserHandle;
228import android.os.UserManager;
229import android.os.UserManagerInternal;
230import android.os.storage.IStorageManager;
231import android.os.storage.StorageEventListener;
232import android.os.storage.StorageManager;
233import android.os.storage.StorageManagerInternal;
234import android.os.storage.VolumeInfo;
235import android.os.storage.VolumeRecord;
236import android.provider.Settings.Global;
237import android.provider.Settings.Secure;
238import android.security.KeyStore;
239import android.security.SystemKeyStore;
240import android.service.pm.PackageServiceDumpProto;
241import android.system.ErrnoException;
242import android.system.Os;
243import android.text.TextUtils;
244import android.text.format.DateUtils;
245import android.util.ArrayMap;
246import android.util.ArraySet;
247import android.util.Base64;
248import android.util.ByteStringUtils;
249import android.util.DisplayMetrics;
250import android.util.EventLog;
251import android.util.ExceptionUtils;
252import android.util.Log;
253import android.util.LogPrinter;
254import android.util.LongSparseArray;
255import android.util.LongSparseLongArray;
256import android.util.MathUtils;
257import android.util.PackageUtils;
258import android.util.Pair;
259import android.util.PrintStreamPrinter;
260import android.util.Slog;
261import android.util.SparseArray;
262import android.util.SparseBooleanArray;
263import android.util.SparseIntArray;
264import android.util.TimingsTraceLog;
265import android.util.Xml;
266import android.util.jar.StrictJarFile;
267import android.util.proto.ProtoOutputStream;
268import android.view.Display;
269
270import com.android.internal.R;
271import com.android.internal.annotations.GuardedBy;
272import com.android.internal.app.IMediaContainerService;
273import com.android.internal.app.ResolverActivity;
274import com.android.internal.content.NativeLibraryHelper;
275import com.android.internal.content.PackageHelper;
276import com.android.internal.logging.MetricsLogger;
277import com.android.internal.os.IParcelFileDescriptorFactory;
278import com.android.internal.os.SomeArgs;
279import com.android.internal.os.Zygote;
280import com.android.internal.telephony.CarrierAppUtils;
281import com.android.internal.util.ArrayUtils;
282import com.android.internal.util.ConcurrentUtils;
283import com.android.internal.util.DumpUtils;
284import com.android.internal.util.FastXmlSerializer;
285import com.android.internal.util.IndentingPrintWriter;
286import com.android.internal.util.Preconditions;
287import com.android.internal.util.XmlUtils;
288import com.android.server.AttributeCache;
289import com.android.server.DeviceIdleController;
290import com.android.server.EventLogTags;
291import com.android.server.FgThread;
292import com.android.server.IntentResolver;
293import com.android.server.LocalServices;
294import com.android.server.LockGuard;
295import com.android.server.ServiceThread;
296import com.android.server.SystemConfig;
297import com.android.server.SystemServerInitThreadPool;
298import com.android.server.Watchdog;
299import com.android.server.net.NetworkPolicyManagerInternal;
300import com.android.server.pm.Installer.InstallerException;
301import com.android.server.pm.Settings.DatabaseVersion;
302import com.android.server.pm.Settings.VersionInfo;
303import com.android.server.pm.dex.ArtManagerService;
304import com.android.server.pm.dex.DexLogger;
305import com.android.server.pm.dex.DexManager;
306import com.android.server.pm.dex.DexoptOptions;
307import com.android.server.pm.dex.PackageDexUsage;
308import com.android.server.pm.permission.BasePermission;
309import com.android.server.pm.permission.DefaultPermissionGrantPolicy;
310import com.android.server.pm.permission.PermissionManagerService;
311import com.android.server.pm.permission.PermissionManagerInternal;
312import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback;
313import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback;
314import com.android.server.pm.permission.PermissionsState;
315import com.android.server.pm.permission.PermissionsState.PermissionState;
316import com.android.server.security.VerityUtils;
317import com.android.server.storage.DeviceStorageMonitorInternal;
318
319import dalvik.system.CloseGuard;
320import dalvik.system.VMRuntime;
321
322import libcore.io.IoUtils;
323
324import org.xmlpull.v1.XmlPullParser;
325import org.xmlpull.v1.XmlPullParserException;
326import org.xmlpull.v1.XmlSerializer;
327
328import java.io.BufferedOutputStream;
329import java.io.ByteArrayInputStream;
330import java.io.ByteArrayOutputStream;
331import java.io.File;
332import java.io.FileDescriptor;
333import java.io.FileInputStream;
334import java.io.FileOutputStream;
335import java.io.FilenameFilter;
336import java.io.IOException;
337import java.io.PrintWriter;
338import java.lang.annotation.Retention;
339import java.lang.annotation.RetentionPolicy;
340import java.nio.charset.StandardCharsets;
341import java.security.DigestException;
342import java.security.DigestInputStream;
343import java.security.MessageDigest;
344import java.security.NoSuchAlgorithmException;
345import java.security.PublicKey;
346import java.security.SecureRandom;
347import java.security.cert.CertificateException;
348import java.util.ArrayList;
349import java.util.Arrays;
350import java.util.Collection;
351import java.util.Collections;
352import java.util.Comparator;
353import java.util.HashMap;
354import java.util.HashSet;
355import java.util.Iterator;
356import java.util.LinkedHashSet;
357import java.util.List;
358import java.util.Map;
359import java.util.Objects;
360import java.util.Set;
361import java.util.concurrent.CountDownLatch;
362import java.util.concurrent.Future;
363import java.util.concurrent.TimeUnit;
364import java.util.concurrent.atomic.AtomicBoolean;
365import java.util.concurrent.atomic.AtomicInteger;
366
367/**
368 * Keep track of all those APKs everywhere.
369 * <p>
370 * Internally there are two important locks:
371 * <ul>
372 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
373 * and other related state. It is a fine-grained lock that should only be held
374 * momentarily, as it's one of the most contended locks in the system.
375 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
376 * operations typically involve heavy lifting of application data on disk. Since
377 * {@code installd} is single-threaded, and it's operations can often be slow,
378 * this lock should never be acquired while already holding {@link #mPackages}.
379 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
380 * holding {@link #mInstallLock}.
381 * </ul>
382 * Many internal methods rely on the caller to hold the appropriate locks, and
383 * this contract is expressed through method name suffixes:
384 * <ul>
385 * <li>fooLI(): the caller must hold {@link #mInstallLock}
386 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
387 * being modified must be frozen
388 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
389 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
390 * </ul>
391 * <p>
392 * Because this class is very central to the platform's security; please run all
393 * CTS and unit tests whenever making modifications:
394 *
395 * <pre>
396 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
397 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
398 * </pre>
399 */
400public class PackageManagerService extends IPackageManager.Stub
401        implements PackageSender {
402    static final String TAG = "PackageManager";
403    public static final boolean DEBUG_SETTINGS = false;
404    static final boolean DEBUG_PREFERRED = false;
405    static final boolean DEBUG_UPGRADE = false;
406    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
407    private static final boolean DEBUG_BACKUP = false;
408    public static final boolean DEBUG_INSTALL = false;
409    public static final boolean DEBUG_REMOVE = true;
410    private static final boolean DEBUG_BROADCASTS = false;
411    private static final boolean DEBUG_SHOW_INFO = false;
412    private static final boolean DEBUG_PACKAGE_INFO = false;
413    private static final boolean DEBUG_INTENT_MATCHING = false;
414    public static final boolean DEBUG_PACKAGE_SCANNING = false;
415    private static final boolean DEBUG_VERIFY = false;
416    private static final boolean DEBUG_FILTERS = false;
417    public static final boolean DEBUG_PERMISSIONS = false;
418    private static final boolean DEBUG_SHARED_LIBRARIES = false;
419    public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
420
421    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
422    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
423    // user, but by default initialize to this.
424    public static final boolean DEBUG_DEXOPT = false;
425
426    private static final boolean DEBUG_ABI_SELECTION = false;
427    private static final boolean DEBUG_INSTANT = Build.IS_DEBUGGABLE;
428    private static final boolean DEBUG_TRIAGED_MISSING = false;
429    private static final boolean DEBUG_APP_DATA = false;
430
431    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
432    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
433
434    private static final boolean HIDE_EPHEMERAL_APIS = false;
435
436    private static final boolean ENABLE_FREE_CACHE_V2 =
437            SystemProperties.getBoolean("fw.free_cache_v2", true);
438
439    private static final int RADIO_UID = Process.PHONE_UID;
440    private static final int LOG_UID = Process.LOG_UID;
441    private static final int NFC_UID = Process.NFC_UID;
442    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
443    private static final int SHELL_UID = Process.SHELL_UID;
444    private static final int SE_UID = Process.SE_UID;
445
446    // Suffix used during package installation when copying/moving
447    // package apks to install directory.
448    private static final String INSTALL_PACKAGE_SUFFIX = "-";
449
450    static final int SCAN_NO_DEX = 1<<0;
451    static final int SCAN_UPDATE_SIGNATURE = 1<<1;
452    static final int SCAN_NEW_INSTALL = 1<<2;
453    static final int SCAN_UPDATE_TIME = 1<<3;
454    static final int SCAN_BOOTING = 1<<4;
455    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<6;
456    static final int SCAN_REQUIRE_KNOWN = 1<<7;
457    static final int SCAN_MOVE = 1<<8;
458    static final int SCAN_INITIAL = 1<<9;
459    static final int SCAN_CHECK_ONLY = 1<<10;
460    static final int SCAN_DONT_KILL_APP = 1<<11;
461    static final int SCAN_IGNORE_FROZEN = 1<<12;
462    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<13;
463    static final int SCAN_AS_INSTANT_APP = 1<<14;
464    static final int SCAN_AS_FULL_APP = 1<<15;
465    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<16;
466    static final int SCAN_AS_SYSTEM = 1<<17;
467    static final int SCAN_AS_PRIVILEGED = 1<<18;
468    static final int SCAN_AS_OEM = 1<<19;
469    static final int SCAN_AS_VENDOR = 1<<20;
470    static final int SCAN_AS_PRODUCT = 1<<21;
471
472    @IntDef(flag = true, prefix = { "SCAN_" }, value = {
473            SCAN_NO_DEX,
474            SCAN_UPDATE_SIGNATURE,
475            SCAN_NEW_INSTALL,
476            SCAN_UPDATE_TIME,
477            SCAN_BOOTING,
478            SCAN_DELETE_DATA_ON_FAILURES,
479            SCAN_REQUIRE_KNOWN,
480            SCAN_MOVE,
481            SCAN_INITIAL,
482            SCAN_CHECK_ONLY,
483            SCAN_DONT_KILL_APP,
484            SCAN_IGNORE_FROZEN,
485            SCAN_FIRST_BOOT_OR_UPGRADE,
486            SCAN_AS_INSTANT_APP,
487            SCAN_AS_FULL_APP,
488            SCAN_AS_VIRTUAL_PRELOAD,
489    })
490    @Retention(RetentionPolicy.SOURCE)
491    public @interface ScanFlags {}
492
493    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
494    /** Extension of the compressed packages */
495    public final static String COMPRESSED_EXTENSION = ".gz";
496    /** Suffix of stub packages on the system partition */
497    public final static String STUB_SUFFIX = "-Stub";
498
499    private static final int[] EMPTY_INT_ARRAY = new int[0];
500
501    private static final int TYPE_UNKNOWN = 0;
502    private static final int TYPE_ACTIVITY = 1;
503    private static final int TYPE_RECEIVER = 2;
504    private static final int TYPE_SERVICE = 3;
505    private static final int TYPE_PROVIDER = 4;
506    @IntDef(prefix = { "TYPE_" }, value = {
507            TYPE_UNKNOWN,
508            TYPE_ACTIVITY,
509            TYPE_RECEIVER,
510            TYPE_SERVICE,
511            TYPE_PROVIDER,
512    })
513    @Retention(RetentionPolicy.SOURCE)
514    public @interface ComponentType {}
515
516    /**
517     * Timeout (in milliseconds) after which the watchdog should declare that
518     * our handler thread is wedged.  The usual default for such things is one
519     * minute but we sometimes do very lengthy I/O operations on this thread,
520     * such as installing multi-gigabyte applications, so ours needs to be longer.
521     */
522    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
523
524    /**
525     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
526     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
527     * settings entry if available, otherwise we use the hardcoded default.  If it's been
528     * more than this long since the last fstrim, we force one during the boot sequence.
529     *
530     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
531     * one gets run at the next available charging+idle time.  This final mandatory
532     * no-fstrim check kicks in only of the other scheduling criteria is never met.
533     */
534    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
535
536    /**
537     * Whether verification is enabled by default.
538     */
539    private static final boolean DEFAULT_VERIFY_ENABLE = true;
540
541    /**
542     * The default maximum time to wait for the verification agent to return in
543     * milliseconds.
544     */
545    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
546
547    /**
548     * The default response for package verification timeout.
549     *
550     * This can be either PackageManager.VERIFICATION_ALLOW or
551     * PackageManager.VERIFICATION_REJECT.
552     */
553    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
554
555    public static final String PLATFORM_PACKAGE_NAME = "android";
556
557    public static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
558
559    public static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
560            DEFAULT_CONTAINER_PACKAGE,
561            "com.android.defcontainer.DefaultContainerService");
562
563    private static final String KILL_APP_REASON_GIDS_CHANGED =
564            "permission grant or revoke changed gids";
565
566    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
567            "permissions revoked";
568
569    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
570
571    private static final String PACKAGE_SCHEME = "package";
572
573    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
574
575    private static final String PRODUCT_OVERLAY_DIR = "/product/overlay";
576
577    private static final String PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB = "pm.dexopt.priv-apps-oob";
578
579    /** Canonical intent used to identify what counts as a "web browser" app */
580    private static final Intent sBrowserIntent;
581    static {
582        sBrowserIntent = new Intent();
583        sBrowserIntent.setAction(Intent.ACTION_VIEW);
584        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
585        sBrowserIntent.setData(Uri.parse("http:"));
586        sBrowserIntent.addFlags(Intent.FLAG_IGNORE_EPHEMERAL);
587    }
588
589    /**
590     * The set of all protected actions [i.e. those actions for which a high priority
591     * intent filter is disallowed].
592     */
593    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
594    static {
595        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
596        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
597        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
598        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
599    }
600
601    // Compilation reasons.
602    public static final int REASON_UNKNOWN = -1;
603    public static final int REASON_FIRST_BOOT = 0;
604    public static final int REASON_BOOT = 1;
605    public static final int REASON_INSTALL = 2;
606    public static final int REASON_BACKGROUND_DEXOPT = 3;
607    public static final int REASON_AB_OTA = 4;
608    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
609    public static final int REASON_SHARED = 6;
610
611    public static final int REASON_LAST = REASON_SHARED;
612
613    /**
614     * Version number for the package parser cache. Increment this whenever the format or
615     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
616     */
617    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
618
619    /**
620     * Whether the package parser cache is enabled.
621     */
622    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
623
624    /**
625     * Permissions required in order to receive instant application lifecycle broadcasts.
626     */
627    private static final String[] INSTANT_APP_BROADCAST_PERMISSION =
628            new String[] { android.Manifest.permission.ACCESS_INSTANT_APPS };
629
630    final ServiceThread mHandlerThread;
631
632    final PackageHandler mHandler;
633
634    private final ProcessLoggingHandler mProcessLoggingHandler;
635
636    /**
637     * Messages for {@link #mHandler} that need to wait for system ready before
638     * being dispatched.
639     */
640    private ArrayList<Message> mPostSystemReadyMessages;
641
642    final int mSdkVersion = Build.VERSION.SDK_INT;
643
644    final Context mContext;
645    final boolean mFactoryTest;
646    final boolean mOnlyCore;
647    final DisplayMetrics mMetrics;
648    final int mDefParseFlags;
649    final String[] mSeparateProcesses;
650    final boolean mIsUpgrade;
651    final boolean mIsPreNUpgrade;
652    final boolean mIsPreNMR1Upgrade;
653
654    // Have we told the Activity Manager to whitelist the default container service by uid yet?
655    @GuardedBy("mPackages")
656    boolean mDefaultContainerWhitelisted = false;
657
658    @GuardedBy("mPackages")
659    private boolean mDexOptDialogShown;
660
661    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
662    // LOCK HELD.  Can be called with mInstallLock held.
663    @GuardedBy("mInstallLock")
664    final Installer mInstaller;
665
666    /** Directory where installed applications are stored */
667    private static final File sAppInstallDir =
668            new File(Environment.getDataDirectory(), "app");
669    /** Directory where installed application's 32-bit native libraries are copied. */
670    private static final File sAppLib32InstallDir =
671            new File(Environment.getDataDirectory(), "app-lib");
672    /** Directory where code and non-resource assets of forward-locked applications are stored */
673    private static final File sDrmAppPrivateInstallDir =
674            new File(Environment.getDataDirectory(), "app-private");
675
676    // ----------------------------------------------------------------
677
678    // Lock for state used when installing and doing other long running
679    // operations.  Methods that must be called with this lock held have
680    // the suffix "LI".
681    final Object mInstallLock = new Object();
682
683    // ----------------------------------------------------------------
684
685    // Keys are String (package name), values are Package.  This also serves
686    // as the lock for the global state.  Methods that must be called with
687    // this lock held have the prefix "LP".
688    @GuardedBy("mPackages")
689    final ArrayMap<String, PackageParser.Package> mPackages =
690            new ArrayMap<String, PackageParser.Package>();
691
692    final ArrayMap<String, Set<String>> mKnownCodebase =
693            new ArrayMap<String, Set<String>>();
694
695    // Keys are isolated uids and values are the uid of the application
696    // that created the isolated proccess.
697    @GuardedBy("mPackages")
698    final SparseIntArray mIsolatedOwners = new SparseIntArray();
699
700    /**
701     * Tracks new system packages [received in an OTA] that we expect to
702     * find updated user-installed versions. Keys are package name, values
703     * are package location.
704     */
705    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
706    /**
707     * Tracks high priority intent filters for protected actions. During boot, certain
708     * filter actions are protected and should never be allowed to have a high priority
709     * intent filter for them. However, there is one, and only one exception -- the
710     * setup wizard. It must be able to define a high priority intent filter for these
711     * actions to ensure there are no escapes from the wizard. We need to delay processing
712     * of these during boot as we need to look at all of the system packages in order
713     * to know which component is the setup wizard.
714     */
715    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
716    /**
717     * Whether or not processing protected filters should be deferred.
718     */
719    private boolean mDeferProtectedFilters = true;
720
721    /**
722     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
723     */
724    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
725    /**
726     * Whether or not system app permissions should be promoted from install to runtime.
727     */
728    boolean mPromoteSystemApps;
729
730    @GuardedBy("mPackages")
731    final Settings mSettings;
732
733    /**
734     * Set of package names that are currently "frozen", which means active
735     * surgery is being done on the code/data for that package. The platform
736     * will refuse to launch frozen packages to avoid race conditions.
737     *
738     * @see PackageFreezer
739     */
740    @GuardedBy("mPackages")
741    final ArraySet<String> mFrozenPackages = new ArraySet<>();
742
743    final ProtectedPackages mProtectedPackages;
744
745    @GuardedBy("mLoadedVolumes")
746    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
747
748    boolean mFirstBoot;
749
750    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
751
752    @GuardedBy("mAvailableFeatures")
753    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
754
755    private final InstantAppRegistry mInstantAppRegistry;
756
757    @GuardedBy("mPackages")
758    int mChangedPackagesSequenceNumber;
759    /**
760     * List of changed [installed, removed or updated] packages.
761     * mapping from user id -> sequence number -> package name
762     */
763    @GuardedBy("mPackages")
764    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
765    /**
766     * The sequence number of the last change to a package.
767     * mapping from user id -> package name -> sequence number
768     */
769    @GuardedBy("mPackages")
770    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
771
772    @GuardedBy("mPackages")
773    final private ArraySet<PackageListObserver> mPackageListObservers = new ArraySet<>();
774
775    class PackageParserCallback implements PackageParser.Callback {
776        @Override public final boolean hasFeature(String feature) {
777            return PackageManagerService.this.hasSystemFeature(feature, 0);
778        }
779
780        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
781                Collection<PackageParser.Package> allPackages, String targetPackageName) {
782            List<PackageParser.Package> overlayPackages = null;
783            for (PackageParser.Package p : allPackages) {
784                if (targetPackageName.equals(p.mOverlayTarget) && p.mOverlayIsStatic) {
785                    if (overlayPackages == null) {
786                        overlayPackages = new ArrayList<PackageParser.Package>();
787                    }
788                    overlayPackages.add(p);
789                }
790            }
791            if (overlayPackages != null) {
792                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
793                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
794                        return p1.mOverlayPriority - p2.mOverlayPriority;
795                    }
796                };
797                Collections.sort(overlayPackages, cmp);
798            }
799            return overlayPackages;
800        }
801
802        @GuardedBy("mInstallLock")
803        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
804                String targetPackageName, String targetPath) {
805            if ("android".equals(targetPackageName)) {
806                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
807                // native AssetManager.
808                return null;
809            }
810            List<PackageParser.Package> overlayPackages =
811                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
812            if (overlayPackages == null || overlayPackages.isEmpty()) {
813                return null;
814            }
815            List<String> overlayPathList = null;
816            for (PackageParser.Package overlayPackage : overlayPackages) {
817                if (targetPath == null) {
818                    if (overlayPathList == null) {
819                        overlayPathList = new ArrayList<String>();
820                    }
821                    overlayPathList.add(overlayPackage.baseCodePath);
822                    continue;
823                }
824
825                try {
826                    // Creates idmaps for system to parse correctly the Android manifest of the
827                    // target package.
828                    //
829                    // OverlayManagerService will update each of them with a correct gid from its
830                    // target package app id.
831                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
832                            UserHandle.getSharedAppGid(
833                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
834                    if (overlayPathList == null) {
835                        overlayPathList = new ArrayList<String>();
836                    }
837                    overlayPathList.add(overlayPackage.baseCodePath);
838                } catch (InstallerException e) {
839                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
840                            overlayPackage.baseCodePath);
841                }
842            }
843            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
844        }
845
846        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
847            synchronized (mPackages) {
848                return getStaticOverlayPathsLocked(
849                        mPackages.values(), targetPackageName, targetPath);
850            }
851        }
852
853        @Override public final String[] getOverlayApks(String targetPackageName) {
854            return getStaticOverlayPaths(targetPackageName, null);
855        }
856
857        @Override public final String[] getOverlayPaths(String targetPackageName,
858                String targetPath) {
859            return getStaticOverlayPaths(targetPackageName, targetPath);
860        }
861    }
862
863    class ParallelPackageParserCallback extends PackageParserCallback {
864        List<PackageParser.Package> mOverlayPackages = null;
865
866        void findStaticOverlayPackages() {
867            synchronized (mPackages) {
868                for (PackageParser.Package p : mPackages.values()) {
869                    if (p.mOverlayIsStatic) {
870                        if (mOverlayPackages == null) {
871                            mOverlayPackages = new ArrayList<PackageParser.Package>();
872                        }
873                        mOverlayPackages.add(p);
874                    }
875                }
876            }
877        }
878
879        @Override
880        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
881            // We can trust mOverlayPackages without holding mPackages because package uninstall
882            // can't happen while running parallel parsing.
883            // Moreover holding mPackages on each parsing thread causes dead-lock.
884            return mOverlayPackages == null ? null :
885                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
886        }
887    }
888
889    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
890    final ParallelPackageParserCallback mParallelPackageParserCallback =
891            new ParallelPackageParserCallback();
892
893    public static final class SharedLibraryEntry {
894        public final @Nullable String path;
895        public final @Nullable String apk;
896        public final @NonNull SharedLibraryInfo info;
897
898        SharedLibraryEntry(String _path, String _apk, String name, long version, int type,
899                String declaringPackageName, long declaringPackageVersionCode) {
900            path = _path;
901            apk = _apk;
902            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
903                    declaringPackageName, declaringPackageVersionCode), null);
904        }
905    }
906
907    // Currently known shared libraries.
908    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
909    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
910            new ArrayMap<>();
911
912    // All available activities, for your resolving pleasure.
913    final ActivityIntentResolver mActivities =
914            new ActivityIntentResolver();
915
916    // All available receivers, for your resolving pleasure.
917    final ActivityIntentResolver mReceivers =
918            new ActivityIntentResolver();
919
920    // All available services, for your resolving pleasure.
921    final ServiceIntentResolver mServices = new ServiceIntentResolver();
922
923    // All available providers, for your resolving pleasure.
924    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
925
926    // Mapping from provider base names (first directory in content URI codePath)
927    // to the provider information.
928    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
929            new ArrayMap<String, PackageParser.Provider>();
930
931    // Mapping from instrumentation class names to info about them.
932    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
933            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
934
935    // Packages whose data we have transfered into another package, thus
936    // should no longer exist.
937    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
938
939    // Broadcast actions that are only available to the system.
940    @GuardedBy("mProtectedBroadcasts")
941    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
942
943    /** List of packages waiting for verification. */
944    final SparseArray<PackageVerificationState> mPendingVerification
945            = new SparseArray<PackageVerificationState>();
946
947    final PackageInstallerService mInstallerService;
948
949    final ArtManagerService mArtManagerService;
950
951    private final PackageDexOptimizer mPackageDexOptimizer;
952    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
953    // is used by other apps).
954    private final DexManager mDexManager;
955
956    private AtomicInteger mNextMoveId = new AtomicInteger();
957    private final MoveCallbacks mMoveCallbacks;
958
959    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
960
961    // Cache of users who need badging.
962    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
963
964    /** Token for keys in mPendingVerification. */
965    private int mPendingVerificationToken = 0;
966
967    volatile boolean mSystemReady;
968    volatile boolean mSafeMode;
969    volatile boolean mHasSystemUidErrors;
970    private volatile boolean mWebInstantAppsDisabled;
971
972    ApplicationInfo mAndroidApplication;
973    final ActivityInfo mResolveActivity = new ActivityInfo();
974    final ResolveInfo mResolveInfo = new ResolveInfo();
975    ComponentName mResolveComponentName;
976    PackageParser.Package mPlatformPackage;
977    ComponentName mCustomResolverComponentName;
978
979    boolean mResolverReplaced = false;
980
981    private final @Nullable ComponentName mIntentFilterVerifierComponent;
982    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
983
984    private int mIntentFilterVerificationToken = 0;
985
986    /** The service connection to the ephemeral resolver */
987    final InstantAppResolverConnection mInstantAppResolverConnection;
988    /** Component used to show resolver settings for Instant Apps */
989    final ComponentName mInstantAppResolverSettingsComponent;
990
991    /** Activity used to install instant applications */
992    ActivityInfo mInstantAppInstallerActivity;
993    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
994
995    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
996            = new SparseArray<IntentFilterVerificationState>();
997
998    // TODO remove this and go through mPermissonManager directly
999    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1000    private final PermissionManagerInternal mPermissionManager;
1001
1002    // List of packages names to keep cached, even if they are uninstalled for all users
1003    private List<String> mKeepUninstalledPackages;
1004
1005    private UserManagerInternal mUserManagerInternal;
1006    private ActivityManagerInternal mActivityManagerInternal;
1007
1008    private DeviceIdleController.LocalService mDeviceIdleController;
1009
1010    private File mCacheDir;
1011
1012    private Future<?> mPrepareAppDataFuture;
1013
1014    private static class IFVerificationParams {
1015        PackageParser.Package pkg;
1016        boolean replacing;
1017        int userId;
1018        int verifierUid;
1019
1020        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1021                int _userId, int _verifierUid) {
1022            pkg = _pkg;
1023            replacing = _replacing;
1024            userId = _userId;
1025            replacing = _replacing;
1026            verifierUid = _verifierUid;
1027        }
1028    }
1029
1030    private interface IntentFilterVerifier<T extends IntentFilter> {
1031        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1032                                               T filter, String packageName);
1033        void startVerifications(int userId);
1034        void receiveVerificationResponse(int verificationId);
1035    }
1036
1037    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1038        private Context mContext;
1039        private ComponentName mIntentFilterVerifierComponent;
1040        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1041
1042        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1043            mContext = context;
1044            mIntentFilterVerifierComponent = verifierComponent;
1045        }
1046
1047        private String getDefaultScheme() {
1048            return IntentFilter.SCHEME_HTTPS;
1049        }
1050
1051        @Override
1052        public void startVerifications(int userId) {
1053            // Launch verifications requests
1054            int count = mCurrentIntentFilterVerifications.size();
1055            for (int n=0; n<count; n++) {
1056                int verificationId = mCurrentIntentFilterVerifications.get(n);
1057                final IntentFilterVerificationState ivs =
1058                        mIntentFilterVerificationStates.get(verificationId);
1059
1060                String packageName = ivs.getPackageName();
1061
1062                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1063                final int filterCount = filters.size();
1064                ArraySet<String> domainsSet = new ArraySet<>();
1065                for (int m=0; m<filterCount; m++) {
1066                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1067                    domainsSet.addAll(filter.getHostsList());
1068                }
1069                synchronized (mPackages) {
1070                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1071                            packageName, domainsSet) != null) {
1072                        scheduleWriteSettingsLocked();
1073                    }
1074                }
1075                sendVerificationRequest(verificationId, ivs);
1076            }
1077            mCurrentIntentFilterVerifications.clear();
1078        }
1079
1080        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1081            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1082            verificationIntent.putExtra(
1083                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1084                    verificationId);
1085            verificationIntent.putExtra(
1086                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1087                    getDefaultScheme());
1088            verificationIntent.putExtra(
1089                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1090                    ivs.getHostsString());
1091            verificationIntent.putExtra(
1092                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1093                    ivs.getPackageName());
1094            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1095            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1096
1097            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1098            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1099                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1100                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1101
1102            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1103            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1104                    "Sending IntentFilter verification broadcast");
1105        }
1106
1107        public void receiveVerificationResponse(int verificationId) {
1108            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1109
1110            final boolean verified = ivs.isVerified();
1111
1112            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1113            final int count = filters.size();
1114            if (DEBUG_DOMAIN_VERIFICATION) {
1115                Slog.i(TAG, "Received verification response " + verificationId
1116                        + " for " + count + " filters, verified=" + verified);
1117            }
1118            for (int n=0; n<count; n++) {
1119                PackageParser.ActivityIntentInfo filter = filters.get(n);
1120                filter.setVerified(verified);
1121
1122                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1123                        + " verified with result:" + verified + " and hosts:"
1124                        + ivs.getHostsString());
1125            }
1126
1127            mIntentFilterVerificationStates.remove(verificationId);
1128
1129            final String packageName = ivs.getPackageName();
1130            IntentFilterVerificationInfo ivi = null;
1131
1132            synchronized (mPackages) {
1133                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1134            }
1135            if (ivi == null) {
1136                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1137                        + verificationId + " packageName:" + packageName);
1138                return;
1139            }
1140            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1141                    "Updating IntentFilterVerificationInfo for package " + packageName
1142                            +" verificationId:" + verificationId);
1143
1144            synchronized (mPackages) {
1145                if (verified) {
1146                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1147                } else {
1148                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1149                }
1150                scheduleWriteSettingsLocked();
1151
1152                final int userId = ivs.getUserId();
1153                if (userId != UserHandle.USER_ALL) {
1154                    final int userStatus =
1155                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1156
1157                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1158                    boolean needUpdate = false;
1159
1160                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1161                    // already been set by the User thru the Disambiguation dialog
1162                    switch (userStatus) {
1163                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1164                            if (verified) {
1165                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1166                            } else {
1167                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1168                            }
1169                            needUpdate = true;
1170                            break;
1171
1172                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1173                            if (verified) {
1174                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1175                                needUpdate = true;
1176                            }
1177                            break;
1178
1179                        default:
1180                            // Nothing to do
1181                    }
1182
1183                    if (needUpdate) {
1184                        mSettings.updateIntentFilterVerificationStatusLPw(
1185                                packageName, updatedStatus, userId);
1186                        scheduleWritePackageRestrictionsLocked(userId);
1187                    }
1188                }
1189            }
1190        }
1191
1192        @Override
1193        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1194                    ActivityIntentInfo filter, String packageName) {
1195            if (!hasValidDomains(filter)) {
1196                return false;
1197            }
1198            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1199            if (ivs == null) {
1200                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1201                        packageName);
1202            }
1203            if (DEBUG_DOMAIN_VERIFICATION) {
1204                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1205            }
1206            ivs.addFilter(filter);
1207            return true;
1208        }
1209
1210        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1211                int userId, int verificationId, String packageName) {
1212            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1213                    verifierUid, userId, packageName);
1214            ivs.setPendingState();
1215            synchronized (mPackages) {
1216                mIntentFilterVerificationStates.append(verificationId, ivs);
1217                mCurrentIntentFilterVerifications.add(verificationId);
1218            }
1219            return ivs;
1220        }
1221    }
1222
1223    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1224        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1225                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1226                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1227    }
1228
1229    // Set of pending broadcasts for aggregating enable/disable of components.
1230    static class PendingPackageBroadcasts {
1231        // for each user id, a map of <package name -> components within that package>
1232        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1233
1234        public PendingPackageBroadcasts() {
1235            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1236        }
1237
1238        public ArrayList<String> get(int userId, String packageName) {
1239            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1240            return packages.get(packageName);
1241        }
1242
1243        public void put(int userId, String packageName, ArrayList<String> components) {
1244            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1245            packages.put(packageName, components);
1246        }
1247
1248        public void remove(int userId, String packageName) {
1249            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1250            if (packages != null) {
1251                packages.remove(packageName);
1252            }
1253        }
1254
1255        public void remove(int userId) {
1256            mUidMap.remove(userId);
1257        }
1258
1259        public int userIdCount() {
1260            return mUidMap.size();
1261        }
1262
1263        public int userIdAt(int n) {
1264            return mUidMap.keyAt(n);
1265        }
1266
1267        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1268            return mUidMap.get(userId);
1269        }
1270
1271        public int size() {
1272            // total number of pending broadcast entries across all userIds
1273            int num = 0;
1274            for (int i = 0; i< mUidMap.size(); i++) {
1275                num += mUidMap.valueAt(i).size();
1276            }
1277            return num;
1278        }
1279
1280        public void clear() {
1281            mUidMap.clear();
1282        }
1283
1284        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1285            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1286            if (map == null) {
1287                map = new ArrayMap<String, ArrayList<String>>();
1288                mUidMap.put(userId, map);
1289            }
1290            return map;
1291        }
1292    }
1293    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1294
1295    // Service Connection to remote media container service to copy
1296    // package uri's from external media onto secure containers
1297    // or internal storage.
1298    private IMediaContainerService mContainerService = null;
1299
1300    static final int SEND_PENDING_BROADCAST = 1;
1301    static final int MCS_BOUND = 3;
1302    static final int END_COPY = 4;
1303    static final int INIT_COPY = 5;
1304    static final int MCS_UNBIND = 6;
1305    static final int START_CLEANING_PACKAGE = 7;
1306    static final int FIND_INSTALL_LOC = 8;
1307    static final int POST_INSTALL = 9;
1308    static final int MCS_RECONNECT = 10;
1309    static final int MCS_GIVE_UP = 11;
1310    static final int WRITE_SETTINGS = 13;
1311    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1312    static final int PACKAGE_VERIFIED = 15;
1313    static final int CHECK_PENDING_VERIFICATION = 16;
1314    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1315    static final int INTENT_FILTER_VERIFIED = 18;
1316    static final int WRITE_PACKAGE_LIST = 19;
1317    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1318
1319    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1320
1321    // Delay time in millisecs
1322    static final int BROADCAST_DELAY = 10 * 1000;
1323
1324    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1325            2 * 60 * 60 * 1000L; /* two hours */
1326
1327    static UserManagerService sUserManager;
1328
1329    // Stores a list of users whose package restrictions file needs to be updated
1330    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1331
1332    final private DefaultContainerConnection mDefContainerConn =
1333            new DefaultContainerConnection();
1334    class DefaultContainerConnection implements ServiceConnection {
1335        public void onServiceConnected(ComponentName name, IBinder service) {
1336            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1337            final IMediaContainerService imcs = IMediaContainerService.Stub
1338                    .asInterface(Binder.allowBlocking(service));
1339            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1340        }
1341
1342        public void onServiceDisconnected(ComponentName name) {
1343            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1344        }
1345    }
1346
1347    // Recordkeeping of restore-after-install operations that are currently in flight
1348    // between the Package Manager and the Backup Manager
1349    static class PostInstallData {
1350        public InstallArgs args;
1351        public PackageInstalledInfo res;
1352
1353        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1354            args = _a;
1355            res = _r;
1356        }
1357    }
1358
1359    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1360    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1361
1362    // XML tags for backup/restore of various bits of state
1363    private static final String TAG_PREFERRED_BACKUP = "pa";
1364    private static final String TAG_DEFAULT_APPS = "da";
1365    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1366
1367    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1368    private static final String TAG_ALL_GRANTS = "rt-grants";
1369    private static final String TAG_GRANT = "grant";
1370    private static final String ATTR_PACKAGE_NAME = "pkg";
1371
1372    private static final String TAG_PERMISSION = "perm";
1373    private static final String ATTR_PERMISSION_NAME = "name";
1374    private static final String ATTR_IS_GRANTED = "g";
1375    private static final String ATTR_USER_SET = "set";
1376    private static final String ATTR_USER_FIXED = "fixed";
1377    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1378
1379    // System/policy permission grants are not backed up
1380    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1381            FLAG_PERMISSION_POLICY_FIXED
1382            | FLAG_PERMISSION_SYSTEM_FIXED
1383            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1384
1385    // And we back up these user-adjusted states
1386    private static final int USER_RUNTIME_GRANT_MASK =
1387            FLAG_PERMISSION_USER_SET
1388            | FLAG_PERMISSION_USER_FIXED
1389            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1390
1391    final @Nullable String mRequiredVerifierPackage;
1392    final @NonNull String mRequiredInstallerPackage;
1393    final @NonNull String mRequiredUninstallerPackage;
1394    final @Nullable String mSetupWizardPackage;
1395    final @Nullable String mStorageManagerPackage;
1396    final @Nullable String mSystemTextClassifierPackage;
1397    final @NonNull String mServicesSystemSharedLibraryPackageName;
1398    final @NonNull String mSharedSystemSharedLibraryPackageName;
1399
1400    private final PackageUsage mPackageUsage = new PackageUsage();
1401    private final CompilerStats mCompilerStats = new CompilerStats();
1402
1403    class PackageHandler extends Handler {
1404        private boolean mBound = false;
1405        final ArrayList<HandlerParams> mPendingInstalls =
1406            new ArrayList<HandlerParams>();
1407
1408        private boolean connectToService() {
1409            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1410                    " DefaultContainerService");
1411            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1412            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1413            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1414                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1415                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1416                mBound = true;
1417                return true;
1418            }
1419            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1420            return false;
1421        }
1422
1423        private void disconnectService() {
1424            mContainerService = null;
1425            mBound = false;
1426            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1427            mContext.unbindService(mDefContainerConn);
1428            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1429        }
1430
1431        PackageHandler(Looper looper) {
1432            super(looper);
1433        }
1434
1435        public void handleMessage(Message msg) {
1436            try {
1437                doHandleMessage(msg);
1438            } finally {
1439                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1440            }
1441        }
1442
1443        void doHandleMessage(Message msg) {
1444            switch (msg.what) {
1445                case INIT_COPY: {
1446                    HandlerParams params = (HandlerParams) msg.obj;
1447                    int idx = mPendingInstalls.size();
1448                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1449                    // If a bind was already initiated we dont really
1450                    // need to do anything. The pending install
1451                    // will be processed later on.
1452                    if (!mBound) {
1453                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1454                                System.identityHashCode(mHandler));
1455                        // If this is the only one pending we might
1456                        // have to bind to the service again.
1457                        if (!connectToService()) {
1458                            Slog.e(TAG, "Failed to bind to media container service");
1459                            params.serviceError();
1460                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1461                                    System.identityHashCode(mHandler));
1462                            if (params.traceMethod != null) {
1463                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1464                                        params.traceCookie);
1465                            }
1466                            return;
1467                        } else {
1468                            // Once we bind to the service, the first
1469                            // pending request will be processed.
1470                            mPendingInstalls.add(idx, params);
1471                        }
1472                    } else {
1473                        mPendingInstalls.add(idx, params);
1474                        // Already bound to the service. Just make
1475                        // sure we trigger off processing the first request.
1476                        if (idx == 0) {
1477                            mHandler.sendEmptyMessage(MCS_BOUND);
1478                        }
1479                    }
1480                    break;
1481                }
1482                case MCS_BOUND: {
1483                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1484                    if (msg.obj != null) {
1485                        mContainerService = (IMediaContainerService) msg.obj;
1486                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1487                                System.identityHashCode(mHandler));
1488                    }
1489                    if (mContainerService == null) {
1490                        if (!mBound) {
1491                            // Something seriously wrong since we are not bound and we are not
1492                            // waiting for connection. Bail out.
1493                            Slog.e(TAG, "Cannot bind to media container service");
1494                            for (HandlerParams params : mPendingInstalls) {
1495                                // Indicate service bind error
1496                                params.serviceError();
1497                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1498                                        System.identityHashCode(params));
1499                                if (params.traceMethod != null) {
1500                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1501                                            params.traceMethod, params.traceCookie);
1502                                }
1503                                return;
1504                            }
1505                            mPendingInstalls.clear();
1506                        } else {
1507                            Slog.w(TAG, "Waiting to connect to media container service");
1508                        }
1509                    } else if (mPendingInstalls.size() > 0) {
1510                        HandlerParams params = mPendingInstalls.get(0);
1511                        if (params != null) {
1512                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1513                                    System.identityHashCode(params));
1514                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1515                            if (params.startCopy()) {
1516                                // We are done...  look for more work or to
1517                                // go idle.
1518                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1519                                        "Checking for more work or unbind...");
1520                                // Delete pending install
1521                                if (mPendingInstalls.size() > 0) {
1522                                    mPendingInstalls.remove(0);
1523                                }
1524                                if (mPendingInstalls.size() == 0) {
1525                                    if (mBound) {
1526                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1527                                                "Posting delayed MCS_UNBIND");
1528                                        removeMessages(MCS_UNBIND);
1529                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1530                                        // Unbind after a little delay, to avoid
1531                                        // continual thrashing.
1532                                        sendMessageDelayed(ubmsg, 10000);
1533                                    }
1534                                } else {
1535                                    // There are more pending requests in queue.
1536                                    // Just post MCS_BOUND message to trigger processing
1537                                    // of next pending install.
1538                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1539                                            "Posting MCS_BOUND for next work");
1540                                    mHandler.sendEmptyMessage(MCS_BOUND);
1541                                }
1542                            }
1543                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1544                        }
1545                    } else {
1546                        // Should never happen ideally.
1547                        Slog.w(TAG, "Empty queue");
1548                    }
1549                    break;
1550                }
1551                case MCS_RECONNECT: {
1552                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1553                    if (mPendingInstalls.size() > 0) {
1554                        if (mBound) {
1555                            disconnectService();
1556                        }
1557                        if (!connectToService()) {
1558                            Slog.e(TAG, "Failed to bind to media container service");
1559                            for (HandlerParams params : mPendingInstalls) {
1560                                // Indicate service bind error
1561                                params.serviceError();
1562                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1563                                        System.identityHashCode(params));
1564                            }
1565                            mPendingInstalls.clear();
1566                        }
1567                    }
1568                    break;
1569                }
1570                case MCS_UNBIND: {
1571                    // If there is no actual work left, then time to unbind.
1572                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1573
1574                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1575                        if (mBound) {
1576                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1577
1578                            disconnectService();
1579                        }
1580                    } else if (mPendingInstalls.size() > 0) {
1581                        // There are more pending requests in queue.
1582                        // Just post MCS_BOUND message to trigger processing
1583                        // of next pending install.
1584                        mHandler.sendEmptyMessage(MCS_BOUND);
1585                    }
1586
1587                    break;
1588                }
1589                case MCS_GIVE_UP: {
1590                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1591                    HandlerParams params = mPendingInstalls.remove(0);
1592                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1593                            System.identityHashCode(params));
1594                    break;
1595                }
1596                case SEND_PENDING_BROADCAST: {
1597                    String packages[];
1598                    ArrayList<String> components[];
1599                    int size = 0;
1600                    int uids[];
1601                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1602                    synchronized (mPackages) {
1603                        if (mPendingBroadcasts == null) {
1604                            return;
1605                        }
1606                        size = mPendingBroadcasts.size();
1607                        if (size <= 0) {
1608                            // Nothing to be done. Just return
1609                            return;
1610                        }
1611                        packages = new String[size];
1612                        components = new ArrayList[size];
1613                        uids = new int[size];
1614                        int i = 0;  // filling out the above arrays
1615
1616                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1617                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1618                            Iterator<Map.Entry<String, ArrayList<String>>> it
1619                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1620                                            .entrySet().iterator();
1621                            while (it.hasNext() && i < size) {
1622                                Map.Entry<String, ArrayList<String>> ent = it.next();
1623                                packages[i] = ent.getKey();
1624                                components[i] = ent.getValue();
1625                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1626                                uids[i] = (ps != null)
1627                                        ? UserHandle.getUid(packageUserId, ps.appId)
1628                                        : -1;
1629                                i++;
1630                            }
1631                        }
1632                        size = i;
1633                        mPendingBroadcasts.clear();
1634                    }
1635                    // Send broadcasts
1636                    for (int i = 0; i < size; i++) {
1637                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1638                    }
1639                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1640                    break;
1641                }
1642                case START_CLEANING_PACKAGE: {
1643                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1644                    final String packageName = (String)msg.obj;
1645                    final int userId = msg.arg1;
1646                    final boolean andCode = msg.arg2 != 0;
1647                    synchronized (mPackages) {
1648                        if (userId == UserHandle.USER_ALL) {
1649                            int[] users = sUserManager.getUserIds();
1650                            for (int user : users) {
1651                                mSettings.addPackageToCleanLPw(
1652                                        new PackageCleanItem(user, packageName, andCode));
1653                            }
1654                        } else {
1655                            mSettings.addPackageToCleanLPw(
1656                                    new PackageCleanItem(userId, packageName, andCode));
1657                        }
1658                    }
1659                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1660                    startCleaningPackages();
1661                } break;
1662                case POST_INSTALL: {
1663                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1664
1665                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1666                    final boolean didRestore = (msg.arg2 != 0);
1667                    mRunningInstalls.delete(msg.arg1);
1668
1669                    if (data != null) {
1670                        InstallArgs args = data.args;
1671                        PackageInstalledInfo parentRes = data.res;
1672
1673                        final boolean grantPermissions = (args.installFlags
1674                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1675                        final boolean killApp = (args.installFlags
1676                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1677                        final boolean virtualPreload = ((args.installFlags
1678                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1679                        final String[] grantedPermissions = args.installGrantPermissions;
1680
1681                        // Handle the parent package
1682                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1683                                virtualPreload, grantedPermissions, didRestore,
1684                                args.installerPackageName, args.observer);
1685
1686                        // Handle the child packages
1687                        final int childCount = (parentRes.addedChildPackages != null)
1688                                ? parentRes.addedChildPackages.size() : 0;
1689                        for (int i = 0; i < childCount; i++) {
1690                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1691                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1692                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1693                                    args.installerPackageName, args.observer);
1694                        }
1695
1696                        // Log tracing if needed
1697                        if (args.traceMethod != null) {
1698                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1699                                    args.traceCookie);
1700                        }
1701                    } else {
1702                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1703                    }
1704
1705                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1706                } break;
1707                case WRITE_SETTINGS: {
1708                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1709                    synchronized (mPackages) {
1710                        removeMessages(WRITE_SETTINGS);
1711                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1712                        mSettings.writeLPr();
1713                        mDirtyUsers.clear();
1714                    }
1715                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1716                } break;
1717                case WRITE_PACKAGE_RESTRICTIONS: {
1718                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1719                    synchronized (mPackages) {
1720                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1721                        for (int userId : mDirtyUsers) {
1722                            mSettings.writePackageRestrictionsLPr(userId);
1723                        }
1724                        mDirtyUsers.clear();
1725                    }
1726                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1727                } break;
1728                case WRITE_PACKAGE_LIST: {
1729                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1730                    synchronized (mPackages) {
1731                        removeMessages(WRITE_PACKAGE_LIST);
1732                        mSettings.writePackageListLPr(msg.arg1);
1733                    }
1734                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1735                } break;
1736                case CHECK_PENDING_VERIFICATION: {
1737                    final int verificationId = msg.arg1;
1738                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1739
1740                    if ((state != null) && !state.timeoutExtended()) {
1741                        final InstallArgs args = state.getInstallArgs();
1742                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1743
1744                        Slog.i(TAG, "Verification timed out for " + originUri);
1745                        mPendingVerification.remove(verificationId);
1746
1747                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1748
1749                        final UserHandle user = args.getUser();
1750                        if (getDefaultVerificationResponse(user)
1751                                == PackageManager.VERIFICATION_ALLOW) {
1752                            Slog.i(TAG, "Continuing with installation of " + originUri);
1753                            state.setVerifierResponse(Binder.getCallingUid(),
1754                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1755                            broadcastPackageVerified(verificationId, originUri,
1756                                    PackageManager.VERIFICATION_ALLOW, user);
1757                            try {
1758                                ret = args.copyApk(mContainerService, true);
1759                            } catch (RemoteException e) {
1760                                Slog.e(TAG, "Could not contact the ContainerService");
1761                            }
1762                        } else {
1763                            broadcastPackageVerified(verificationId, originUri,
1764                                    PackageManager.VERIFICATION_REJECT, user);
1765                        }
1766
1767                        Trace.asyncTraceEnd(
1768                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1769
1770                        processPendingInstall(args, ret);
1771                        mHandler.sendEmptyMessage(MCS_UNBIND);
1772                    }
1773                    break;
1774                }
1775                case PACKAGE_VERIFIED: {
1776                    final int verificationId = msg.arg1;
1777
1778                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1779                    if (state == null) {
1780                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1781                        break;
1782                    }
1783
1784                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1785
1786                    state.setVerifierResponse(response.callerUid, response.code);
1787
1788                    if (state.isVerificationComplete()) {
1789                        mPendingVerification.remove(verificationId);
1790
1791                        final InstallArgs args = state.getInstallArgs();
1792                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1793
1794                        int ret;
1795                        if (state.isInstallAllowed()) {
1796                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1797                            broadcastPackageVerified(verificationId, originUri,
1798                                    response.code, state.getInstallArgs().getUser());
1799                            try {
1800                                ret = args.copyApk(mContainerService, true);
1801                            } catch (RemoteException e) {
1802                                Slog.e(TAG, "Could not contact the ContainerService");
1803                            }
1804                        } else {
1805                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1806                        }
1807
1808                        Trace.asyncTraceEnd(
1809                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1810
1811                        processPendingInstall(args, ret);
1812                        mHandler.sendEmptyMessage(MCS_UNBIND);
1813                    }
1814
1815                    break;
1816                }
1817                case START_INTENT_FILTER_VERIFICATIONS: {
1818                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1819                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1820                            params.replacing, params.pkg);
1821                    break;
1822                }
1823                case INTENT_FILTER_VERIFIED: {
1824                    final int verificationId = msg.arg1;
1825
1826                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1827                            verificationId);
1828                    if (state == null) {
1829                        Slog.w(TAG, "Invalid IntentFilter verification token "
1830                                + verificationId + " received");
1831                        break;
1832                    }
1833
1834                    final int userId = state.getUserId();
1835
1836                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1837                            "Processing IntentFilter verification with token:"
1838                            + verificationId + " and userId:" + userId);
1839
1840                    final IntentFilterVerificationResponse response =
1841                            (IntentFilterVerificationResponse) msg.obj;
1842
1843                    state.setVerifierResponse(response.callerUid, response.code);
1844
1845                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1846                            "IntentFilter verification with token:" + verificationId
1847                            + " and userId:" + userId
1848                            + " is settings verifier response with response code:"
1849                            + response.code);
1850
1851                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1852                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1853                                + response.getFailedDomainsString());
1854                    }
1855
1856                    if (state.isVerificationComplete()) {
1857                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1858                    } else {
1859                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1860                                "IntentFilter verification with token:" + verificationId
1861                                + " was not said to be complete");
1862                    }
1863
1864                    break;
1865                }
1866                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1867                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1868                            mInstantAppResolverConnection,
1869                            (InstantAppRequest) msg.obj,
1870                            mInstantAppInstallerActivity,
1871                            mHandler);
1872                }
1873            }
1874        }
1875    }
1876
1877    private PermissionCallback mPermissionCallback = new PermissionCallback() {
1878        @Override
1879        public void onGidsChanged(int appId, int userId) {
1880            mHandler.post(new Runnable() {
1881                @Override
1882                public void run() {
1883                    killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
1884                }
1885            });
1886        }
1887        @Override
1888        public void onPermissionGranted(int uid, int userId) {
1889            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1890
1891            // Not critical; if this is lost, the application has to request again.
1892            synchronized (mPackages) {
1893                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1894            }
1895        }
1896        @Override
1897        public void onInstallPermissionGranted() {
1898            synchronized (mPackages) {
1899                scheduleWriteSettingsLocked();
1900            }
1901        }
1902        @Override
1903        public void onPermissionRevoked(int uid, int userId) {
1904            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1905
1906            synchronized (mPackages) {
1907                // Critical; after this call the application should never have the permission
1908                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
1909            }
1910
1911            final int appId = UserHandle.getAppId(uid);
1912            killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
1913        }
1914        @Override
1915        public void onInstallPermissionRevoked() {
1916            synchronized (mPackages) {
1917                scheduleWriteSettingsLocked();
1918            }
1919        }
1920        @Override
1921        public void onPermissionUpdated(int[] updatedUserIds, boolean sync) {
1922            synchronized (mPackages) {
1923                for (int userId : updatedUserIds) {
1924                    mSettings.writeRuntimePermissionsForUserLPr(userId, sync);
1925                }
1926            }
1927        }
1928        @Override
1929        public void onInstallPermissionUpdated() {
1930            synchronized (mPackages) {
1931                scheduleWriteSettingsLocked();
1932            }
1933        }
1934        @Override
1935        public void onPermissionRemoved() {
1936            synchronized (mPackages) {
1937                mSettings.writeLPr();
1938            }
1939        }
1940    };
1941
1942    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1943            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1944            boolean launchedForRestore, String installerPackage,
1945            IPackageInstallObserver2 installObserver) {
1946        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1947            // Send the removed broadcasts
1948            if (res.removedInfo != null) {
1949                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1950            }
1951
1952            // Now that we successfully installed the package, grant runtime
1953            // permissions if requested before broadcasting the install. Also
1954            // for legacy apps in permission review mode we clear the permission
1955            // review flag which is used to emulate runtime permissions for
1956            // legacy apps.
1957            if (grantPermissions) {
1958                final int callingUid = Binder.getCallingUid();
1959                mPermissionManager.grantRequestedRuntimePermissions(
1960                        res.pkg, res.newUsers, grantedPermissions, callingUid,
1961                        mPermissionCallback);
1962            }
1963
1964            final boolean update = res.removedInfo != null
1965                    && res.removedInfo.removedPackage != null;
1966            final String installerPackageName =
1967                    res.installerPackageName != null
1968                            ? res.installerPackageName
1969                            : res.removedInfo != null
1970                                    ? res.removedInfo.installerPackageName
1971                                    : null;
1972
1973            // If this is the first time we have child packages for a disabled privileged
1974            // app that had no children, we grant requested runtime permissions to the new
1975            // children if the parent on the system image had them already granted.
1976            if (res.pkg.parentPackage != null) {
1977                final int callingUid = Binder.getCallingUid();
1978                mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage(
1979                        res.pkg, callingUid, mPermissionCallback);
1980            }
1981
1982            synchronized (mPackages) {
1983                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1984            }
1985
1986            final String packageName = res.pkg.applicationInfo.packageName;
1987
1988            // Determine the set of users who are adding this package for
1989            // the first time vs. those who are seeing an update.
1990            int[] firstUserIds = EMPTY_INT_ARRAY;
1991            int[] firstInstantUserIds = EMPTY_INT_ARRAY;
1992            int[] updateUserIds = EMPTY_INT_ARRAY;
1993            int[] instantUserIds = EMPTY_INT_ARRAY;
1994            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1995            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1996            for (int newUser : res.newUsers) {
1997                final boolean isInstantApp = ps.getInstantApp(newUser);
1998                if (allNewUsers) {
1999                    if (isInstantApp) {
2000                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2001                    } else {
2002                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2003                    }
2004                    continue;
2005                }
2006                boolean isNew = true;
2007                for (int origUser : res.origUsers) {
2008                    if (origUser == newUser) {
2009                        isNew = false;
2010                        break;
2011                    }
2012                }
2013                if (isNew) {
2014                    if (isInstantApp) {
2015                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2016                    } else {
2017                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2018                    }
2019                } else {
2020                    if (isInstantApp) {
2021                        instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser);
2022                    } else {
2023                        updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser);
2024                    }
2025                }
2026            }
2027
2028            // Send installed broadcasts if the package is not a static shared lib.
2029            if (res.pkg.staticSharedLibName == null) {
2030                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
2031
2032                // Send added for users that see the package for the first time
2033                // sendPackageAddedForNewUsers also deals with system apps
2034                int appId = UserHandle.getAppId(res.uid);
2035                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
2036                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
2037                        virtualPreload /*startReceiver*/, appId, firstUserIds, firstInstantUserIds);
2038
2039                // Send added for users that don't see the package for the first time
2040                Bundle extras = new Bundle(1);
2041                extras.putInt(Intent.EXTRA_UID, res.uid);
2042                if (update) {
2043                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2044                }
2045                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2046                        extras, 0 /*flags*/,
2047                        null /*targetPackage*/, null /*finishedReceiver*/,
2048                        updateUserIds, instantUserIds);
2049                if (installerPackageName != null) {
2050                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2051                            extras, 0 /*flags*/,
2052                            installerPackageName, null /*finishedReceiver*/,
2053                            updateUserIds, instantUserIds);
2054                }
2055
2056                // Send replaced for users that don't see the package for the first time
2057                if (update) {
2058                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2059                            packageName, extras, 0 /*flags*/,
2060                            null /*targetPackage*/, null /*finishedReceiver*/,
2061                            updateUserIds, instantUserIds);
2062                    if (installerPackageName != null) {
2063                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2064                                extras, 0 /*flags*/,
2065                                installerPackageName, null /*finishedReceiver*/,
2066                                updateUserIds, instantUserIds);
2067                    }
2068                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2069                            null /*package*/, null /*extras*/, 0 /*flags*/,
2070                            packageName /*targetPackage*/,
2071                            null /*finishedReceiver*/, updateUserIds, instantUserIds);
2072                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2073                    // First-install and we did a restore, so we're responsible for the
2074                    // first-launch broadcast.
2075                    if (DEBUG_BACKUP) {
2076                        Slog.i(TAG, "Post-restore of " + packageName
2077                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds));
2078                    }
2079                    sendFirstLaunchBroadcast(packageName, installerPackage,
2080                            firstUserIds, firstInstantUserIds);
2081                }
2082
2083                // Send broadcast package appeared if forward locked/external for all users
2084                // treat asec-hosted packages like removable media on upgrade
2085                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2086                    if (DEBUG_INSTALL) {
2087                        Slog.i(TAG, "upgrading pkg " + res.pkg
2088                                + " is ASEC-hosted -> AVAILABLE");
2089                    }
2090                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2091                    ArrayList<String> pkgList = new ArrayList<>(1);
2092                    pkgList.add(packageName);
2093                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2094                }
2095            }
2096
2097            // Work that needs to happen on first install within each user
2098            if (firstUserIds != null && firstUserIds.length > 0) {
2099                synchronized (mPackages) {
2100                    for (int userId : firstUserIds) {
2101                        // If this app is a browser and it's newly-installed for some
2102                        // users, clear any default-browser state in those users. The
2103                        // app's nature doesn't depend on the user, so we can just check
2104                        // its browser nature in any user and generalize.
2105                        if (packageIsBrowser(packageName, userId)) {
2106                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2107                        }
2108
2109                        // We may also need to apply pending (restored) runtime
2110                        // permission grants within these users.
2111                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2112                    }
2113                }
2114            }
2115
2116            if (allNewUsers && !update) {
2117                notifyPackageAdded(packageName);
2118            }
2119
2120            // Log current value of "unknown sources" setting
2121            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2122                    getUnknownSourcesSettings());
2123
2124            // Remove the replaced package's older resources safely now
2125            // We delete after a gc for applications  on sdcard.
2126            if (res.removedInfo != null && res.removedInfo.args != null) {
2127                Runtime.getRuntime().gc();
2128                synchronized (mInstallLock) {
2129                    res.removedInfo.args.doPostDeleteLI(true);
2130                }
2131            } else {
2132                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2133                // and not block here.
2134                VMRuntime.getRuntime().requestConcurrentGC();
2135            }
2136
2137            // Notify DexManager that the package was installed for new users.
2138            // The updated users should already be indexed and the package code paths
2139            // should not change.
2140            // Don't notify the manager for ephemeral apps as they are not expected to
2141            // survive long enough to benefit of background optimizations.
2142            for (int userId : firstUserIds) {
2143                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2144                // There's a race currently where some install events may interleave with an uninstall.
2145                // This can lead to package info being null (b/36642664).
2146                if (info != null) {
2147                    mDexManager.notifyPackageInstalled(info, userId);
2148                }
2149            }
2150        }
2151
2152        // If someone is watching installs - notify them
2153        if (installObserver != null) {
2154            try {
2155                Bundle extras = extrasForInstallResult(res);
2156                installObserver.onPackageInstalled(res.name, res.returnCode,
2157                        res.returnMsg, extras);
2158            } catch (RemoteException e) {
2159                Slog.i(TAG, "Observer no longer exists.");
2160            }
2161        }
2162    }
2163
2164    private StorageEventListener mStorageListener = new StorageEventListener() {
2165        @Override
2166        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2167            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2168                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2169                    final String volumeUuid = vol.getFsUuid();
2170
2171                    // Clean up any users or apps that were removed or recreated
2172                    // while this volume was missing
2173                    sUserManager.reconcileUsers(volumeUuid);
2174                    reconcileApps(volumeUuid);
2175
2176                    // Clean up any install sessions that expired or were
2177                    // cancelled while this volume was missing
2178                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2179
2180                    loadPrivatePackages(vol);
2181
2182                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2183                    unloadPrivatePackages(vol);
2184                }
2185            }
2186        }
2187
2188        @Override
2189        public void onVolumeForgotten(String fsUuid) {
2190            if (TextUtils.isEmpty(fsUuid)) {
2191                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2192                return;
2193            }
2194
2195            // Remove any apps installed on the forgotten volume
2196            synchronized (mPackages) {
2197                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2198                for (PackageSetting ps : packages) {
2199                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2200                    deletePackageVersioned(new VersionedPackage(ps.name,
2201                            PackageManager.VERSION_CODE_HIGHEST),
2202                            new LegacyPackageDeleteObserver(null).getBinder(),
2203                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2204                    // Try very hard to release any references to this package
2205                    // so we don't risk the system server being killed due to
2206                    // open FDs
2207                    AttributeCache.instance().removePackage(ps.name);
2208                }
2209
2210                mSettings.onVolumeForgotten(fsUuid);
2211                mSettings.writeLPr();
2212            }
2213        }
2214    };
2215
2216    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2217        Bundle extras = null;
2218        switch (res.returnCode) {
2219            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2220                extras = new Bundle();
2221                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2222                        res.origPermission);
2223                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2224                        res.origPackage);
2225                break;
2226            }
2227            case PackageManager.INSTALL_SUCCEEDED: {
2228                extras = new Bundle();
2229                extras.putBoolean(Intent.EXTRA_REPLACING,
2230                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2231                break;
2232            }
2233        }
2234        return extras;
2235    }
2236
2237    void scheduleWriteSettingsLocked() {
2238        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2239            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2240        }
2241    }
2242
2243    void scheduleWritePackageListLocked(int userId) {
2244        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2245            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2246            msg.arg1 = userId;
2247            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2248        }
2249    }
2250
2251    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2252        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2253        scheduleWritePackageRestrictionsLocked(userId);
2254    }
2255
2256    void scheduleWritePackageRestrictionsLocked(int userId) {
2257        final int[] userIds = (userId == UserHandle.USER_ALL)
2258                ? sUserManager.getUserIds() : new int[]{userId};
2259        for (int nextUserId : userIds) {
2260            if (!sUserManager.exists(nextUserId)) return;
2261            mDirtyUsers.add(nextUserId);
2262            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2263                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2264            }
2265        }
2266    }
2267
2268    public static PackageManagerService main(Context context, Installer installer,
2269            boolean factoryTest, boolean onlyCore) {
2270        // Self-check for initial settings.
2271        PackageManagerServiceCompilerMapping.checkProperties();
2272
2273        PackageManagerService m = new PackageManagerService(context, installer,
2274                factoryTest, onlyCore);
2275        m.enableSystemUserPackages();
2276        ServiceManager.addService("package", m);
2277        final PackageManagerNative pmn = m.new PackageManagerNative();
2278        ServiceManager.addService("package_native", pmn);
2279        return m;
2280    }
2281
2282    private void enableSystemUserPackages() {
2283        if (!UserManager.isSplitSystemUser()) {
2284            return;
2285        }
2286        // For system user, enable apps based on the following conditions:
2287        // - app is whitelisted or belong to one of these groups:
2288        //   -- system app which has no launcher icons
2289        //   -- system app which has INTERACT_ACROSS_USERS permission
2290        //   -- system IME app
2291        // - app is not in the blacklist
2292        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2293        Set<String> enableApps = new ArraySet<>();
2294        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2295                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2296                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2297        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2298        enableApps.addAll(wlApps);
2299        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2300                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2301        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2302        enableApps.removeAll(blApps);
2303        Log.i(TAG, "Applications installed for system user: " + enableApps);
2304        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2305                UserHandle.SYSTEM);
2306        final int allAppsSize = allAps.size();
2307        synchronized (mPackages) {
2308            for (int i = 0; i < allAppsSize; i++) {
2309                String pName = allAps.get(i);
2310                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2311                // Should not happen, but we shouldn't be failing if it does
2312                if (pkgSetting == null) {
2313                    continue;
2314                }
2315                boolean install = enableApps.contains(pName);
2316                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2317                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2318                            + " for system user");
2319                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2320                }
2321            }
2322            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2323        }
2324    }
2325
2326    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2327        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2328                Context.DISPLAY_SERVICE);
2329        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2330    }
2331
2332    /**
2333     * Requests that files preopted on a secondary system partition be copied to the data partition
2334     * if possible.  Note that the actual copying of the files is accomplished by init for security
2335     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2336     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2337     */
2338    private static void requestCopyPreoptedFiles() {
2339        final int WAIT_TIME_MS = 100;
2340        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2341        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2342            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2343            // We will wait for up to 100 seconds.
2344            final long timeStart = SystemClock.uptimeMillis();
2345            final long timeEnd = timeStart + 100 * 1000;
2346            long timeNow = timeStart;
2347            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2348                try {
2349                    Thread.sleep(WAIT_TIME_MS);
2350                } catch (InterruptedException e) {
2351                    // Do nothing
2352                }
2353                timeNow = SystemClock.uptimeMillis();
2354                if (timeNow > timeEnd) {
2355                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2356                    Slog.wtf(TAG, "cppreopt did not finish!");
2357                    break;
2358                }
2359            }
2360
2361            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2362        }
2363    }
2364
2365    public PackageManagerService(Context context, Installer installer,
2366            boolean factoryTest, boolean onlyCore) {
2367        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2368        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2369        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2370                SystemClock.uptimeMillis());
2371
2372        if (mSdkVersion <= 0) {
2373            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2374        }
2375
2376        mContext = context;
2377
2378        mFactoryTest = factoryTest;
2379        mOnlyCore = onlyCore;
2380        mMetrics = new DisplayMetrics();
2381        mInstaller = installer;
2382
2383        // Create sub-components that provide services / data. Order here is important.
2384        synchronized (mInstallLock) {
2385        synchronized (mPackages) {
2386            // Expose private service for system components to use.
2387            LocalServices.addService(
2388                    PackageManagerInternal.class, new PackageManagerInternalImpl());
2389            sUserManager = new UserManagerService(context, this,
2390                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2391            mPermissionManager = PermissionManagerService.create(context,
2392                    new DefaultPermissionGrantedCallback() {
2393                        @Override
2394                        public void onDefaultRuntimePermissionsGranted(int userId) {
2395                            synchronized(mPackages) {
2396                                mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);
2397                            }
2398                        }
2399                    }, mPackages /*externalLock*/);
2400            mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy();
2401            mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages);
2402        }
2403        }
2404        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2405                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2406        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2407                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2408        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2409                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2410        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2411                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2412        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2413                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2414        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2415                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2416        mSettings.addSharedUserLPw("android.uid.se", SE_UID,
2417                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2418
2419        String separateProcesses = SystemProperties.get("debug.separate_processes");
2420        if (separateProcesses != null && separateProcesses.length() > 0) {
2421            if ("*".equals(separateProcesses)) {
2422                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2423                mSeparateProcesses = null;
2424                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2425            } else {
2426                mDefParseFlags = 0;
2427                mSeparateProcesses = separateProcesses.split(",");
2428                Slog.w(TAG, "Running with debug.separate_processes: "
2429                        + separateProcesses);
2430            }
2431        } else {
2432            mDefParseFlags = 0;
2433            mSeparateProcesses = null;
2434        }
2435
2436        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2437                "*dexopt*");
2438        DexManager.Listener dexManagerListener = DexLogger.getListener(this,
2439                installer, mInstallLock);
2440        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock,
2441                dexManagerListener);
2442        mArtManagerService = new ArtManagerService(this, installer, mInstallLock);
2443        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2444
2445        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2446                FgThread.get().getLooper());
2447
2448        getDefaultDisplayMetrics(context, mMetrics);
2449
2450        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2451        SystemConfig systemConfig = SystemConfig.getInstance();
2452        mAvailableFeatures = systemConfig.getAvailableFeatures();
2453        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2454
2455        mProtectedPackages = new ProtectedPackages(mContext);
2456
2457        synchronized (mInstallLock) {
2458        // writer
2459        synchronized (mPackages) {
2460            mHandlerThread = new ServiceThread(TAG,
2461                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2462            mHandlerThread.start();
2463            mHandler = new PackageHandler(mHandlerThread.getLooper());
2464            mProcessLoggingHandler = new ProcessLoggingHandler();
2465            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2466            mInstantAppRegistry = new InstantAppRegistry(this);
2467
2468            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2469            final int builtInLibCount = libConfig.size();
2470            for (int i = 0; i < builtInLibCount; i++) {
2471                String name = libConfig.keyAt(i);
2472                String path = libConfig.valueAt(i);
2473                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2474                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2475            }
2476
2477            SELinuxMMAC.readInstallPolicy();
2478
2479            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2480            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2481            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2482
2483            // Clean up orphaned packages for which the code path doesn't exist
2484            // and they are an update to a system app - caused by bug/32321269
2485            final int packageSettingCount = mSettings.mPackages.size();
2486            for (int i = packageSettingCount - 1; i >= 0; i--) {
2487                PackageSetting ps = mSettings.mPackages.valueAt(i);
2488                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2489                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2490                    mSettings.mPackages.removeAt(i);
2491                    mSettings.enableSystemPackageLPw(ps.name);
2492                }
2493            }
2494
2495            if (mFirstBoot) {
2496                requestCopyPreoptedFiles();
2497            }
2498
2499            String customResolverActivity = Resources.getSystem().getString(
2500                    R.string.config_customResolverActivity);
2501            if (TextUtils.isEmpty(customResolverActivity)) {
2502                customResolverActivity = null;
2503            } else {
2504                mCustomResolverComponentName = ComponentName.unflattenFromString(
2505                        customResolverActivity);
2506            }
2507
2508            long startTime = SystemClock.uptimeMillis();
2509
2510            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2511                    startTime);
2512
2513            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2514            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2515
2516            if (bootClassPath == null) {
2517                Slog.w(TAG, "No BOOTCLASSPATH found!");
2518            }
2519
2520            if (systemServerClassPath == null) {
2521                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2522            }
2523
2524            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2525
2526            final VersionInfo ver = mSettings.getInternalVersion();
2527            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2528            if (mIsUpgrade) {
2529                logCriticalInfo(Log.INFO,
2530                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2531            }
2532
2533            // when upgrading from pre-M, promote system app permissions from install to runtime
2534            mPromoteSystemApps =
2535                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2536
2537            // When upgrading from pre-N, we need to handle package extraction like first boot,
2538            // as there is no profiling data available.
2539            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2540
2541            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2542
2543            // save off the names of pre-existing system packages prior to scanning; we don't
2544            // want to automatically grant runtime permissions for new system apps
2545            if (mPromoteSystemApps) {
2546                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2547                while (pkgSettingIter.hasNext()) {
2548                    PackageSetting ps = pkgSettingIter.next();
2549                    if (isSystemApp(ps)) {
2550                        mExistingSystemPackages.add(ps.name);
2551                    }
2552                }
2553            }
2554
2555            mCacheDir = preparePackageParserCache(mIsUpgrade);
2556
2557            // Set flag to monitor and not change apk file paths when
2558            // scanning install directories.
2559            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2560
2561            if (mIsUpgrade || mFirstBoot) {
2562                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2563            }
2564
2565            // Collect vendor/product overlay packages. (Do this before scanning any apps.)
2566            // For security and version matching reason, only consider
2567            // overlay packages if they reside in the right directory.
2568            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR),
2569                    mDefParseFlags
2570                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2571                    scanFlags
2572                    | SCAN_AS_SYSTEM
2573                    | SCAN_AS_VENDOR,
2574                    0);
2575            scanDirTracedLI(new File(PRODUCT_OVERLAY_DIR),
2576                    mDefParseFlags
2577                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2578                    scanFlags
2579                    | SCAN_AS_SYSTEM
2580                    | SCAN_AS_PRODUCT,
2581                    0);
2582
2583            mParallelPackageParserCallback.findStaticOverlayPackages();
2584
2585            // Find base frameworks (resource packages without code).
2586            scanDirTracedLI(frameworkDir,
2587                    mDefParseFlags
2588                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2589                    scanFlags
2590                    | SCAN_NO_DEX
2591                    | SCAN_AS_SYSTEM
2592                    | SCAN_AS_PRIVILEGED,
2593                    0);
2594
2595            // Collect privileged system packages.
2596            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2597            scanDirTracedLI(privilegedAppDir,
2598                    mDefParseFlags
2599                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2600                    scanFlags
2601                    | SCAN_AS_SYSTEM
2602                    | SCAN_AS_PRIVILEGED,
2603                    0);
2604
2605            // Collect ordinary system packages.
2606            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2607            scanDirTracedLI(systemAppDir,
2608                    mDefParseFlags
2609                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2610                    scanFlags
2611                    | SCAN_AS_SYSTEM,
2612                    0);
2613
2614            // Collect privileged vendor packages.
2615            File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
2616            try {
2617                privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile();
2618            } catch (IOException e) {
2619                // failed to look up canonical path, continue with original one
2620            }
2621            scanDirTracedLI(privilegedVendorAppDir,
2622                    mDefParseFlags
2623                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2624                    scanFlags
2625                    | SCAN_AS_SYSTEM
2626                    | SCAN_AS_VENDOR
2627                    | SCAN_AS_PRIVILEGED,
2628                    0);
2629
2630            // Collect ordinary vendor packages.
2631            File vendorAppDir = new File(Environment.getVendorDirectory(), "app");
2632            try {
2633                vendorAppDir = vendorAppDir.getCanonicalFile();
2634            } catch (IOException e) {
2635                // failed to look up canonical path, continue with original one
2636            }
2637            scanDirTracedLI(vendorAppDir,
2638                    mDefParseFlags
2639                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2640                    scanFlags
2641                    | SCAN_AS_SYSTEM
2642                    | SCAN_AS_VENDOR,
2643                    0);
2644
2645            // Collect privileged odm packages. /odm is another vendor partition
2646            // other than /vendor.
2647            File privilegedOdmAppDir = new File(Environment.getOdmDirectory(),
2648                        "priv-app");
2649            try {
2650                privilegedOdmAppDir = privilegedOdmAppDir.getCanonicalFile();
2651            } catch (IOException e) {
2652                // failed to look up canonical path, continue with original one
2653            }
2654            scanDirTracedLI(privilegedOdmAppDir,
2655                    mDefParseFlags
2656                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2657                    scanFlags
2658                    | SCAN_AS_SYSTEM
2659                    | SCAN_AS_VENDOR
2660                    | SCAN_AS_PRIVILEGED,
2661                    0);
2662
2663            // Collect ordinary odm packages. /odm is another vendor partition
2664            // other than /vendor.
2665            File odmAppDir = new File(Environment.getOdmDirectory(), "app");
2666            try {
2667                odmAppDir = odmAppDir.getCanonicalFile();
2668            } catch (IOException e) {
2669                // failed to look up canonical path, continue with original one
2670            }
2671            scanDirTracedLI(odmAppDir,
2672                    mDefParseFlags
2673                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2674                    scanFlags
2675                    | SCAN_AS_SYSTEM
2676                    | SCAN_AS_VENDOR,
2677                    0);
2678
2679            // Collect all OEM packages.
2680            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2681            scanDirTracedLI(oemAppDir,
2682                    mDefParseFlags
2683                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2684                    scanFlags
2685                    | SCAN_AS_SYSTEM
2686                    | SCAN_AS_OEM,
2687                    0);
2688
2689            // Collected privileged product packages.
2690            File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
2691            try {
2692                privilegedProductAppDir = privilegedProductAppDir.getCanonicalFile();
2693            } catch (IOException e) {
2694                // failed to look up canonical path, continue with original one
2695            }
2696            scanDirTracedLI(privilegedProductAppDir,
2697                    mDefParseFlags
2698                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2699                    scanFlags
2700                    | SCAN_AS_SYSTEM
2701                    | SCAN_AS_PRODUCT
2702                    | SCAN_AS_PRIVILEGED,
2703                    0);
2704
2705            // Collect ordinary product packages.
2706            File productAppDir = new File(Environment.getProductDirectory(), "app");
2707            try {
2708                productAppDir = productAppDir.getCanonicalFile();
2709            } catch (IOException e) {
2710                // failed to look up canonical path, continue with original one
2711            }
2712            scanDirTracedLI(productAppDir,
2713                    mDefParseFlags
2714                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2715                    scanFlags
2716                    | SCAN_AS_SYSTEM
2717                    | SCAN_AS_PRODUCT,
2718                    0);
2719
2720            // Prune any system packages that no longer exist.
2721            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2722            // Stub packages must either be replaced with full versions in the /data
2723            // partition or be disabled.
2724            final List<String> stubSystemApps = new ArrayList<>();
2725            if (!mOnlyCore) {
2726                // do this first before mucking with mPackages for the "expecting better" case
2727                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2728                while (pkgIterator.hasNext()) {
2729                    final PackageParser.Package pkg = pkgIterator.next();
2730                    if (pkg.isStub) {
2731                        stubSystemApps.add(pkg.packageName);
2732                    }
2733                }
2734
2735                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2736                while (psit.hasNext()) {
2737                    PackageSetting ps = psit.next();
2738
2739                    /*
2740                     * If this is not a system app, it can't be a
2741                     * disable system app.
2742                     */
2743                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2744                        continue;
2745                    }
2746
2747                    /*
2748                     * If the package is scanned, it's not erased.
2749                     */
2750                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2751                    if (scannedPkg != null) {
2752                        /*
2753                         * If the system app is both scanned and in the
2754                         * disabled packages list, then it must have been
2755                         * added via OTA. Remove it from the currently
2756                         * scanned package so the previously user-installed
2757                         * application can be scanned.
2758                         */
2759                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2760                            logCriticalInfo(Log.WARN,
2761                                    "Expecting better updated system app for " + ps.name
2762                                    + "; removing system app.  Last known"
2763                                    + " codePath=" + ps.codePathString
2764                                    + ", versionCode=" + ps.versionCode
2765                                    + "; scanned versionCode=" + scannedPkg.getLongVersionCode());
2766                            removePackageLI(scannedPkg, true);
2767                            mExpectingBetter.put(ps.name, ps.codePath);
2768                        }
2769
2770                        continue;
2771                    }
2772
2773                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2774                        psit.remove();
2775                        logCriticalInfo(Log.WARN, "System package " + ps.name
2776                                + " no longer exists; it's data will be wiped");
2777                        // Actual deletion of code and data will be handled by later
2778                        // reconciliation step
2779                    } else {
2780                        // we still have a disabled system package, but, it still might have
2781                        // been removed. check the code path still exists and check there's
2782                        // still a package. the latter can happen if an OTA keeps the same
2783                        // code path, but, changes the package name.
2784                        final PackageSetting disabledPs =
2785                                mSettings.getDisabledSystemPkgLPr(ps.name);
2786                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2787                                || disabledPs.pkg == null) {
2788                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2789                        }
2790                    }
2791                }
2792            }
2793
2794            //delete tmp files
2795            deleteTempPackageFiles();
2796
2797            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2798
2799            // Remove any shared userIDs that have no associated packages
2800            mSettings.pruneSharedUsersLPw();
2801            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2802            final int systemPackagesCount = mPackages.size();
2803            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2804                    + " ms, packageCount: " + systemPackagesCount
2805                    + " , timePerPackage: "
2806                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2807                    + " , cached: " + cachedSystemApps);
2808            if (mIsUpgrade && systemPackagesCount > 0) {
2809                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2810                        ((int) systemScanTime) / systemPackagesCount);
2811            }
2812            if (!mOnlyCore) {
2813                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2814                        SystemClock.uptimeMillis());
2815                scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2816
2817                scanDirTracedLI(sDrmAppPrivateInstallDir, mDefParseFlags
2818                        | PackageParser.PARSE_FORWARD_LOCK,
2819                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2820
2821                // Remove disable package settings for updated system apps that were
2822                // removed via an OTA. If the update is no longer present, remove the
2823                // app completely. Otherwise, revoke their system privileges.
2824                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2825                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2826                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2827                    final String msg;
2828                    if (deletedPkg == null) {
2829                        // should have found an update, but, we didn't; remove everything
2830                        msg = "Updated system package " + deletedAppName
2831                                + " no longer exists; removing its data";
2832                        // Actual deletion of code and data will be handled by later
2833                        // reconciliation step
2834                    } else {
2835                        // found an update; revoke system privileges
2836                        msg = "Updated system package + " + deletedAppName
2837                                + " no longer exists; revoking system privileges";
2838
2839                        // Don't do anything if a stub is removed from the system image. If
2840                        // we were to remove the uncompressed version from the /data partition,
2841                        // this is where it'd be done.
2842
2843                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2844                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2845                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2846                    }
2847                    logCriticalInfo(Log.WARN, msg);
2848                }
2849
2850                /*
2851                 * Make sure all system apps that we expected to appear on
2852                 * the userdata partition actually showed up. If they never
2853                 * appeared, crawl back and revive the system version.
2854                 */
2855                for (int i = 0; i < mExpectingBetter.size(); i++) {
2856                    final String packageName = mExpectingBetter.keyAt(i);
2857                    if (!mPackages.containsKey(packageName)) {
2858                        final File scanFile = mExpectingBetter.valueAt(i);
2859
2860                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2861                                + " but never showed up; reverting to system");
2862
2863                        final @ParseFlags int reparseFlags;
2864                        final @ScanFlags int rescanFlags;
2865                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2866                            reparseFlags =
2867                                    mDefParseFlags |
2868                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2869                            rescanFlags =
2870                                    scanFlags
2871                                    | SCAN_AS_SYSTEM
2872                                    | SCAN_AS_PRIVILEGED;
2873                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2874                            reparseFlags =
2875                                    mDefParseFlags |
2876                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2877                            rescanFlags =
2878                                    scanFlags
2879                                    | SCAN_AS_SYSTEM;
2880                        } else if (FileUtils.contains(privilegedVendorAppDir, scanFile)
2881                                || FileUtils.contains(privilegedOdmAppDir, scanFile)) {
2882                            reparseFlags =
2883                                    mDefParseFlags |
2884                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2885                            rescanFlags =
2886                                    scanFlags
2887                                    | SCAN_AS_SYSTEM
2888                                    | SCAN_AS_VENDOR
2889                                    | SCAN_AS_PRIVILEGED;
2890                        } else if (FileUtils.contains(vendorAppDir, scanFile)
2891                                || FileUtils.contains(odmAppDir, scanFile)) {
2892                            reparseFlags =
2893                                    mDefParseFlags |
2894                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2895                            rescanFlags =
2896                                    scanFlags
2897                                    | SCAN_AS_SYSTEM
2898                                    | SCAN_AS_VENDOR;
2899                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2900                            reparseFlags =
2901                                    mDefParseFlags |
2902                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2903                            rescanFlags =
2904                                    scanFlags
2905                                    | SCAN_AS_SYSTEM
2906                                    | SCAN_AS_OEM;
2907                        } else if (FileUtils.contains(privilegedProductAppDir, scanFile)) {
2908                            reparseFlags =
2909                                    mDefParseFlags |
2910                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2911                            rescanFlags =
2912                                    scanFlags
2913                                    | SCAN_AS_SYSTEM
2914                                    | SCAN_AS_PRODUCT
2915                                    | SCAN_AS_PRIVILEGED;
2916                        } else if (FileUtils.contains(productAppDir, scanFile)) {
2917                            reparseFlags =
2918                                    mDefParseFlags |
2919                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2920                            rescanFlags =
2921                                    scanFlags
2922                                    | SCAN_AS_SYSTEM
2923                                    | SCAN_AS_PRODUCT;
2924                        } else {
2925                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2926                            continue;
2927                        }
2928
2929                        mSettings.enableSystemPackageLPw(packageName);
2930
2931                        try {
2932                            scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null);
2933                        } catch (PackageManagerException e) {
2934                            Slog.e(TAG, "Failed to parse original system package: "
2935                                    + e.getMessage());
2936                        }
2937                    }
2938                }
2939
2940                // Uncompress and install any stubbed system applications.
2941                // This must be done last to ensure all stubs are replaced or disabled.
2942                decompressSystemApplications(stubSystemApps, scanFlags);
2943
2944                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2945                                - cachedSystemApps;
2946
2947                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2948                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2949                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2950                        + " ms, packageCount: " + dataPackagesCount
2951                        + " , timePerPackage: "
2952                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2953                        + " , cached: " + cachedNonSystemApps);
2954                if (mIsUpgrade && dataPackagesCount > 0) {
2955                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2956                            ((int) dataScanTime) / dataPackagesCount);
2957                }
2958            }
2959            mExpectingBetter.clear();
2960
2961            // Resolve the storage manager.
2962            mStorageManagerPackage = getStorageManagerPackageName();
2963
2964            // Resolve protected action filters. Only the setup wizard is allowed to
2965            // have a high priority filter for these actions.
2966            mSetupWizardPackage = getSetupWizardPackageName();
2967            if (mProtectedFilters.size() > 0) {
2968                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2969                    Slog.i(TAG, "No setup wizard;"
2970                        + " All protected intents capped to priority 0");
2971                }
2972                for (ActivityIntentInfo filter : mProtectedFilters) {
2973                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2974                        if (DEBUG_FILTERS) {
2975                            Slog.i(TAG, "Found setup wizard;"
2976                                + " allow priority " + filter.getPriority() + ";"
2977                                + " package: " + filter.activity.info.packageName
2978                                + " activity: " + filter.activity.className
2979                                + " priority: " + filter.getPriority());
2980                        }
2981                        // skip setup wizard; allow it to keep the high priority filter
2982                        continue;
2983                    }
2984                    if (DEBUG_FILTERS) {
2985                        Slog.i(TAG, "Protected action; cap priority to 0;"
2986                                + " package: " + filter.activity.info.packageName
2987                                + " activity: " + filter.activity.className
2988                                + " origPrio: " + filter.getPriority());
2989                    }
2990                    filter.setPriority(0);
2991                }
2992            }
2993
2994            mSystemTextClassifierPackage = getSystemTextClassifierPackageName();
2995
2996            mDeferProtectedFilters = false;
2997            mProtectedFilters.clear();
2998
2999            // Now that we know all of the shared libraries, update all clients to have
3000            // the correct library paths.
3001            updateAllSharedLibrariesLPw(null);
3002
3003            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
3004                // NOTE: We ignore potential failures here during a system scan (like
3005                // the rest of the commands above) because there's precious little we
3006                // can do about it. A settings error is reported, though.
3007                final List<String> changedAbiCodePath =
3008                        adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
3009                if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
3010                    for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
3011                        final String codePathString = changedAbiCodePath.get(i);
3012                        try {
3013                            mInstaller.rmdex(codePathString,
3014                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
3015                        } catch (InstallerException ignored) {
3016                        }
3017                    }
3018                }
3019                // Adjust seInfo to ensure apps which share a sharedUserId are placed in the same
3020                // SELinux domain.
3021                setting.fixSeInfoLocked();
3022            }
3023
3024            // Now that we know all the packages we are keeping,
3025            // read and update their last usage times.
3026            mPackageUsage.read(mPackages);
3027            mCompilerStats.read();
3028
3029            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
3030                    SystemClock.uptimeMillis());
3031            Slog.i(TAG, "Time to scan packages: "
3032                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
3033                    + " seconds");
3034
3035            // If the platform SDK has changed since the last time we booted,
3036            // we need to re-grant app permission to catch any new ones that
3037            // appear.  This is really a hack, and means that apps can in some
3038            // cases get permissions that the user didn't initially explicitly
3039            // allow...  it would be nice to have some better way to handle
3040            // this situation.
3041            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
3042            if (sdkUpdated) {
3043                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
3044                        + mSdkVersion + "; regranting permissions for internal storage");
3045            }
3046            mPermissionManager.updateAllPermissions(
3047                    StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(),
3048                    mPermissionCallback);
3049            ver.sdkVersion = mSdkVersion;
3050
3051            // If this is the first boot or an update from pre-M, and it is a normal
3052            // boot, then we need to initialize the default preferred apps across
3053            // all defined users.
3054            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
3055                for (UserInfo user : sUserManager.getUsers(true)) {
3056                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
3057                    applyFactoryDefaultBrowserLPw(user.id);
3058                    primeDomainVerificationsLPw(user.id);
3059                }
3060            }
3061
3062            // Prepare storage for system user really early during boot,
3063            // since core system apps like SettingsProvider and SystemUI
3064            // can't wait for user to start
3065            final int storageFlags;
3066            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
3067                storageFlags = StorageManager.FLAG_STORAGE_DE;
3068            } else {
3069                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
3070            }
3071            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
3072                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
3073                    true /* onlyCoreApps */);
3074            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
3075                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
3076                        Trace.TRACE_TAG_PACKAGE_MANAGER);
3077                traceLog.traceBegin("AppDataFixup");
3078                try {
3079                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
3080                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
3081                } catch (InstallerException e) {
3082                    Slog.w(TAG, "Trouble fixing GIDs", e);
3083                }
3084                traceLog.traceEnd();
3085
3086                traceLog.traceBegin("AppDataPrepare");
3087                if (deferPackages == null || deferPackages.isEmpty()) {
3088                    return;
3089                }
3090                int count = 0;
3091                for (String pkgName : deferPackages) {
3092                    PackageParser.Package pkg = null;
3093                    synchronized (mPackages) {
3094                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
3095                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
3096                            pkg = ps.pkg;
3097                        }
3098                    }
3099                    if (pkg != null) {
3100                        synchronized (mInstallLock) {
3101                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
3102                                    true /* maybeMigrateAppData */);
3103                        }
3104                        count++;
3105                    }
3106                }
3107                traceLog.traceEnd();
3108                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
3109            }, "prepareAppData");
3110
3111            // If this is first boot after an OTA, and a normal boot, then
3112            // we need to clear code cache directories.
3113            // Note that we do *not* clear the application profiles. These remain valid
3114            // across OTAs and are used to drive profile verification (post OTA) and
3115            // profile compilation (without waiting to collect a fresh set of profiles).
3116            if (mIsUpgrade && !onlyCore) {
3117                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
3118                for (int i = 0; i < mSettings.mPackages.size(); i++) {
3119                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
3120                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
3121                        // No apps are running this early, so no need to freeze
3122                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
3123                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3124                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3125                    }
3126                }
3127                ver.fingerprint = Build.FINGERPRINT;
3128            }
3129
3130            checkDefaultBrowser();
3131
3132            // clear only after permissions and other defaults have been updated
3133            mExistingSystemPackages.clear();
3134            mPromoteSystemApps = false;
3135
3136            // All the changes are done during package scanning.
3137            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3138
3139            // can downgrade to reader
3140            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3141            mSettings.writeLPr();
3142            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3143            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3144                    SystemClock.uptimeMillis());
3145
3146            if (!mOnlyCore) {
3147                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3148                mRequiredInstallerPackage = getRequiredInstallerLPr();
3149                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3150                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3151                if (mIntentFilterVerifierComponent != null) {
3152                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3153                            mIntentFilterVerifierComponent);
3154                } else {
3155                    mIntentFilterVerifier = null;
3156                }
3157                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3158                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3159                        SharedLibraryInfo.VERSION_UNDEFINED);
3160                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3161                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3162                        SharedLibraryInfo.VERSION_UNDEFINED);
3163            } else {
3164                mRequiredVerifierPackage = null;
3165                mRequiredInstallerPackage = null;
3166                mRequiredUninstallerPackage = null;
3167                mIntentFilterVerifierComponent = null;
3168                mIntentFilterVerifier = null;
3169                mServicesSystemSharedLibraryPackageName = null;
3170                mSharedSystemSharedLibraryPackageName = null;
3171            }
3172
3173            mInstallerService = new PackageInstallerService(context, this);
3174            final Pair<ComponentName, String> instantAppResolverComponent =
3175                    getInstantAppResolverLPr();
3176            if (instantAppResolverComponent != null) {
3177                if (DEBUG_INSTANT) {
3178                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3179                }
3180                mInstantAppResolverConnection = new InstantAppResolverConnection(
3181                        mContext, instantAppResolverComponent.first,
3182                        instantAppResolverComponent.second);
3183                mInstantAppResolverSettingsComponent =
3184                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3185            } else {
3186                mInstantAppResolverConnection = null;
3187                mInstantAppResolverSettingsComponent = null;
3188            }
3189            updateInstantAppInstallerLocked(null);
3190
3191            // Read and update the usage of dex files.
3192            // Do this at the end of PM init so that all the packages have their
3193            // data directory reconciled.
3194            // At this point we know the code paths of the packages, so we can validate
3195            // the disk file and build the internal cache.
3196            // The usage file is expected to be small so loading and verifying it
3197            // should take a fairly small time compare to the other activities (e.g. package
3198            // scanning).
3199            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3200            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3201            for (int userId : currentUserIds) {
3202                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3203            }
3204            mDexManager.load(userPackages);
3205            if (mIsUpgrade) {
3206                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3207                        (int) (SystemClock.uptimeMillis() - startTime));
3208            }
3209        } // synchronized (mPackages)
3210        } // synchronized (mInstallLock)
3211
3212        // Now after opening every single application zip, make sure they
3213        // are all flushed.  Not really needed, but keeps things nice and
3214        // tidy.
3215        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3216        Runtime.getRuntime().gc();
3217        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3218
3219        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3220        FallbackCategoryProvider.loadFallbacks();
3221        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3222
3223        // The initial scanning above does many calls into installd while
3224        // holding the mPackages lock, but we're mostly interested in yelling
3225        // once we have a booted system.
3226        mInstaller.setWarnIfHeld(mPackages);
3227
3228        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3229    }
3230
3231    /**
3232     * Uncompress and install stub applications.
3233     * <p>In order to save space on the system partition, some applications are shipped in a
3234     * compressed form. In addition the compressed bits for the full application, the
3235     * system image contains a tiny stub comprised of only the Android manifest.
3236     * <p>During the first boot, attempt to uncompress and install the full application. If
3237     * the application can't be installed for any reason, disable the stub and prevent
3238     * uncompressing the full application during future boots.
3239     * <p>In order to forcefully attempt an installation of a full application, go to app
3240     * settings and enable the application.
3241     */
3242    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3243        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3244            final String pkgName = stubSystemApps.get(i);
3245            // skip if the system package is already disabled
3246            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3247                stubSystemApps.remove(i);
3248                continue;
3249            }
3250            // skip if the package isn't installed (?!); this should never happen
3251            final PackageParser.Package pkg = mPackages.get(pkgName);
3252            if (pkg == null) {
3253                stubSystemApps.remove(i);
3254                continue;
3255            }
3256            // skip if the package has been disabled by the user
3257            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3258            if (ps != null) {
3259                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3260                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3261                    stubSystemApps.remove(i);
3262                    continue;
3263                }
3264            }
3265
3266            if (DEBUG_COMPRESSION) {
3267                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3268            }
3269
3270            // uncompress the binary to its eventual destination on /data
3271            final File scanFile = decompressPackage(pkg);
3272            if (scanFile == null) {
3273                continue;
3274            }
3275
3276            // install the package to replace the stub on /system
3277            try {
3278                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3279                removePackageLI(pkg, true /*chatty*/);
3280                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3281                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3282                        UserHandle.USER_SYSTEM, "android");
3283                stubSystemApps.remove(i);
3284                continue;
3285            } catch (PackageManagerException e) {
3286                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3287            }
3288
3289            // any failed attempt to install the package will be cleaned up later
3290        }
3291
3292        // disable any stub still left; these failed to install the full application
3293        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3294            final String pkgName = stubSystemApps.get(i);
3295            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3296            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3297                    UserHandle.USER_SYSTEM, "android");
3298            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3299        }
3300    }
3301
3302    /**
3303     * Decompresses the given package on the system image onto
3304     * the /data partition.
3305     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3306     */
3307    private File decompressPackage(PackageParser.Package pkg) {
3308        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3309        if (compressedFiles == null || compressedFiles.length == 0) {
3310            if (DEBUG_COMPRESSION) {
3311                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3312            }
3313            return null;
3314        }
3315        final File dstCodePath =
3316                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3317        int ret = PackageManager.INSTALL_SUCCEEDED;
3318        try {
3319            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3320            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3321            for (File srcFile : compressedFiles) {
3322                final String srcFileName = srcFile.getName();
3323                final String dstFileName = srcFileName.substring(
3324                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3325                final File dstFile = new File(dstCodePath, dstFileName);
3326                ret = decompressFile(srcFile, dstFile);
3327                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3328                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3329                            + "; pkg: " + pkg.packageName
3330                            + ", file: " + dstFileName);
3331                    break;
3332                }
3333            }
3334        } catch (ErrnoException e) {
3335            logCriticalInfo(Log.ERROR, "Failed to decompress"
3336                    + "; pkg: " + pkg.packageName
3337                    + ", err: " + e.errno);
3338        }
3339        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3340            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3341            NativeLibraryHelper.Handle handle = null;
3342            try {
3343                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3344                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3345                        null /*abiOverride*/);
3346            } catch (IOException e) {
3347                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3348                        + "; pkg: " + pkg.packageName);
3349                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3350            } finally {
3351                IoUtils.closeQuietly(handle);
3352            }
3353        }
3354        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3355            if (dstCodePath == null || !dstCodePath.exists()) {
3356                return null;
3357            }
3358            removeCodePathLI(dstCodePath);
3359            return null;
3360        }
3361
3362        return dstCodePath;
3363    }
3364
3365    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3366        // we're only interested in updating the installer appliction when 1) it's not
3367        // already set or 2) the modified package is the installer
3368        if (mInstantAppInstallerActivity != null
3369                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3370                        .equals(modifiedPackage)) {
3371            return;
3372        }
3373        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3374    }
3375
3376    private static File preparePackageParserCache(boolean isUpgrade) {
3377        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3378            return null;
3379        }
3380
3381        // Disable package parsing on eng builds to allow for faster incremental development.
3382        if (Build.IS_ENG) {
3383            return null;
3384        }
3385
3386        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3387            Slog.i(TAG, "Disabling package parser cache due to system property.");
3388            return null;
3389        }
3390
3391        // The base directory for the package parser cache lives under /data/system/.
3392        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3393                "package_cache");
3394        if (cacheBaseDir == null) {
3395            return null;
3396        }
3397
3398        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3399        // This also serves to "GC" unused entries when the package cache version changes (which
3400        // can only happen during upgrades).
3401        if (isUpgrade) {
3402            FileUtils.deleteContents(cacheBaseDir);
3403        }
3404
3405
3406        // Return the versioned package cache directory. This is something like
3407        // "/data/system/package_cache/1"
3408        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3409
3410        if (cacheDir == null) {
3411            // Something went wrong. Attempt to delete everything and return.
3412            Slog.wtf(TAG, "Cache directory cannot be created - wiping base dir " + cacheBaseDir);
3413            FileUtils.deleteContentsAndDir(cacheBaseDir);
3414            return null;
3415        }
3416
3417        // The following is a workaround to aid development on non-numbered userdebug
3418        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3419        // the system partition is newer.
3420        //
3421        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3422        // that starts with "eng." to signify that this is an engineering build and not
3423        // destined for release.
3424        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3425            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3426
3427            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3428            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3429            // in general and should not be used for production changes. In this specific case,
3430            // we know that they will work.
3431            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3432            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3433                FileUtils.deleteContents(cacheBaseDir);
3434                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3435            }
3436        }
3437
3438        return cacheDir;
3439    }
3440
3441    @Override
3442    public boolean isFirstBoot() {
3443        // allow instant applications
3444        return mFirstBoot;
3445    }
3446
3447    @Override
3448    public boolean isOnlyCoreApps() {
3449        // allow instant applications
3450        return mOnlyCore;
3451    }
3452
3453    @Override
3454    public boolean isUpgrade() {
3455        // allow instant applications
3456        // The system property allows testing ota flow when upgraded to the same image.
3457        return mIsUpgrade || SystemProperties.getBoolean(
3458                "persist.pm.mock-upgrade", false /* default */);
3459    }
3460
3461    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3462        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3463
3464        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3465                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3466                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3467        if (matches.size() == 1) {
3468            return matches.get(0).getComponentInfo().packageName;
3469        } else if (matches.size() == 0) {
3470            Log.e(TAG, "There should probably be a verifier, but, none were found");
3471            return null;
3472        }
3473        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3474    }
3475
3476    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3477        synchronized (mPackages) {
3478            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3479            if (libraryEntry == null) {
3480                throw new IllegalStateException("Missing required shared library:" + name);
3481            }
3482            return libraryEntry.apk;
3483        }
3484    }
3485
3486    private @NonNull String getRequiredInstallerLPr() {
3487        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3488        intent.addCategory(Intent.CATEGORY_DEFAULT);
3489        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3490
3491        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3492                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3493                UserHandle.USER_SYSTEM);
3494        if (matches.size() == 1) {
3495            ResolveInfo resolveInfo = matches.get(0);
3496            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3497                throw new RuntimeException("The installer must be a privileged app");
3498            }
3499            return matches.get(0).getComponentInfo().packageName;
3500        } else {
3501            throw new RuntimeException("There must be exactly one installer; found " + matches);
3502        }
3503    }
3504
3505    private @NonNull String getRequiredUninstallerLPr() {
3506        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3507        intent.addCategory(Intent.CATEGORY_DEFAULT);
3508        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3509
3510        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3511                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3512                UserHandle.USER_SYSTEM);
3513        if (resolveInfo == null ||
3514                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3515            throw new RuntimeException("There must be exactly one uninstaller; found "
3516                    + resolveInfo);
3517        }
3518        return resolveInfo.getComponentInfo().packageName;
3519    }
3520
3521    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3522        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3523
3524        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3525                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3526                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3527        ResolveInfo best = null;
3528        final int N = matches.size();
3529        for (int i = 0; i < N; i++) {
3530            final ResolveInfo cur = matches.get(i);
3531            final String packageName = cur.getComponentInfo().packageName;
3532            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3533                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3534                continue;
3535            }
3536
3537            if (best == null || cur.priority > best.priority) {
3538                best = cur;
3539            }
3540        }
3541
3542        if (best != null) {
3543            return best.getComponentInfo().getComponentName();
3544        }
3545        Slog.w(TAG, "Intent filter verifier not found");
3546        return null;
3547    }
3548
3549    @Override
3550    public @Nullable ComponentName getInstantAppResolverComponent() {
3551        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3552            return null;
3553        }
3554        synchronized (mPackages) {
3555            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3556            if (instantAppResolver == null) {
3557                return null;
3558            }
3559            return instantAppResolver.first;
3560        }
3561    }
3562
3563    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3564        final String[] packageArray =
3565                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3566        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3567            if (DEBUG_INSTANT) {
3568                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3569            }
3570            return null;
3571        }
3572
3573        final int callingUid = Binder.getCallingUid();
3574        final int resolveFlags =
3575                MATCH_DIRECT_BOOT_AWARE
3576                | MATCH_DIRECT_BOOT_UNAWARE
3577                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3578        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3579        final Intent resolverIntent = new Intent(actionName);
3580        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3581                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3582        final int N = resolvers.size();
3583        if (N == 0) {
3584            if (DEBUG_INSTANT) {
3585                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3586            }
3587            return null;
3588        }
3589
3590        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3591        for (int i = 0; i < N; i++) {
3592            final ResolveInfo info = resolvers.get(i);
3593
3594            if (info.serviceInfo == null) {
3595                continue;
3596            }
3597
3598            final String packageName = info.serviceInfo.packageName;
3599            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3600                if (DEBUG_INSTANT) {
3601                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3602                            + " pkg: " + packageName + ", info:" + info);
3603                }
3604                continue;
3605            }
3606
3607            if (DEBUG_INSTANT) {
3608                Slog.v(TAG, "Ephemeral resolver found;"
3609                        + " pkg: " + packageName + ", info:" + info);
3610            }
3611            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3612        }
3613        if (DEBUG_INSTANT) {
3614            Slog.v(TAG, "Ephemeral resolver NOT found");
3615        }
3616        return null;
3617    }
3618
3619    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3620        String[] orderedActions = Build.IS_ENG
3621                ? new String[]{
3622                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE + "_TEST",
3623                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE}
3624                : new String[]{
3625                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE};
3626
3627        final int resolveFlags =
3628                MATCH_DIRECT_BOOT_AWARE
3629                        | MATCH_DIRECT_BOOT_UNAWARE
3630                        | Intent.FLAG_IGNORE_EPHEMERAL
3631                        | (!Build.IS_ENG ? MATCH_SYSTEM_ONLY : 0);
3632        final Intent intent = new Intent();
3633        intent.addCategory(Intent.CATEGORY_DEFAULT);
3634        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3635        List<ResolveInfo> matches = null;
3636        for (String action : orderedActions) {
3637            intent.setAction(action);
3638            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3639                    resolveFlags, UserHandle.USER_SYSTEM);
3640            if (matches.isEmpty()) {
3641                if (DEBUG_INSTANT) {
3642                    Slog.d(TAG, "Instant App installer not found with " + action);
3643                }
3644            } else {
3645                break;
3646            }
3647        }
3648        Iterator<ResolveInfo> iter = matches.iterator();
3649        while (iter.hasNext()) {
3650            final ResolveInfo rInfo = iter.next();
3651            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3652            if (ps != null) {
3653                final PermissionsState permissionsState = ps.getPermissionsState();
3654                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)
3655                        || Build.IS_ENG) {
3656                    continue;
3657                }
3658            }
3659            iter.remove();
3660        }
3661        if (matches.size() == 0) {
3662            return null;
3663        } else if (matches.size() == 1) {
3664            return (ActivityInfo) matches.get(0).getComponentInfo();
3665        } else {
3666            throw new RuntimeException(
3667                    "There must be at most one ephemeral installer; found " + matches);
3668        }
3669    }
3670
3671    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3672            @NonNull ComponentName resolver) {
3673        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3674                .addCategory(Intent.CATEGORY_DEFAULT)
3675                .setPackage(resolver.getPackageName());
3676        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3677        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3678                UserHandle.USER_SYSTEM);
3679        if (matches.isEmpty()) {
3680            return null;
3681        }
3682        return matches.get(0).getComponentInfo().getComponentName();
3683    }
3684
3685    private void primeDomainVerificationsLPw(int userId) {
3686        if (DEBUG_DOMAIN_VERIFICATION) {
3687            Slog.d(TAG, "Priming domain verifications in user " + userId);
3688        }
3689
3690        SystemConfig systemConfig = SystemConfig.getInstance();
3691        ArraySet<String> packages = systemConfig.getLinkedApps();
3692
3693        for (String packageName : packages) {
3694            PackageParser.Package pkg = mPackages.get(packageName);
3695            if (pkg != null) {
3696                if (!pkg.isSystem()) {
3697                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3698                    continue;
3699                }
3700
3701                ArraySet<String> domains = null;
3702                for (PackageParser.Activity a : pkg.activities) {
3703                    for (ActivityIntentInfo filter : a.intents) {
3704                        if (hasValidDomains(filter)) {
3705                            if (domains == null) {
3706                                domains = new ArraySet<String>();
3707                            }
3708                            domains.addAll(filter.getHostsList());
3709                        }
3710                    }
3711                }
3712
3713                if (domains != null && domains.size() > 0) {
3714                    if (DEBUG_DOMAIN_VERIFICATION) {
3715                        Slog.v(TAG, "      + " + packageName);
3716                    }
3717                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3718                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3719                    // and then 'always' in the per-user state actually used for intent resolution.
3720                    final IntentFilterVerificationInfo ivi;
3721                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3722                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3723                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3724                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3725                } else {
3726                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3727                            + "' does not handle web links");
3728                }
3729            } else {
3730                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3731            }
3732        }
3733
3734        scheduleWritePackageRestrictionsLocked(userId);
3735        scheduleWriteSettingsLocked();
3736    }
3737
3738    private void applyFactoryDefaultBrowserLPw(int userId) {
3739        // The default browser app's package name is stored in a string resource,
3740        // with a product-specific overlay used for vendor customization.
3741        String browserPkg = mContext.getResources().getString(
3742                com.android.internal.R.string.default_browser);
3743        if (!TextUtils.isEmpty(browserPkg)) {
3744            // non-empty string => required to be a known package
3745            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3746            if (ps == null) {
3747                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3748                browserPkg = null;
3749            } else {
3750                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3751            }
3752        }
3753
3754        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3755        // default.  If there's more than one, just leave everything alone.
3756        if (browserPkg == null) {
3757            calculateDefaultBrowserLPw(userId);
3758        }
3759    }
3760
3761    private void calculateDefaultBrowserLPw(int userId) {
3762        List<String> allBrowsers = resolveAllBrowserApps(userId);
3763        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3764        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3765    }
3766
3767    private List<String> resolveAllBrowserApps(int userId) {
3768        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3769        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3770                PackageManager.MATCH_ALL, userId);
3771
3772        final int count = list.size();
3773        List<String> result = new ArrayList<String>(count);
3774        for (int i=0; i<count; i++) {
3775            ResolveInfo info = list.get(i);
3776            if (info.activityInfo == null
3777                    || !info.handleAllWebDataURI
3778                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3779                    || result.contains(info.activityInfo.packageName)) {
3780                continue;
3781            }
3782            result.add(info.activityInfo.packageName);
3783        }
3784
3785        return result;
3786    }
3787
3788    private boolean packageIsBrowser(String packageName, int userId) {
3789        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3790                PackageManager.MATCH_ALL, userId);
3791        final int N = list.size();
3792        for (int i = 0; i < N; i++) {
3793            ResolveInfo info = list.get(i);
3794            if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) {
3795                return true;
3796            }
3797        }
3798        return false;
3799    }
3800
3801    private void checkDefaultBrowser() {
3802        final int myUserId = UserHandle.myUserId();
3803        final String packageName = getDefaultBrowserPackageName(myUserId);
3804        if (packageName != null) {
3805            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3806            if (info == null) {
3807                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3808                synchronized (mPackages) {
3809                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3810                }
3811            }
3812        }
3813    }
3814
3815    @Override
3816    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3817            throws RemoteException {
3818        try {
3819            return super.onTransact(code, data, reply, flags);
3820        } catch (RuntimeException e) {
3821            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3822                Slog.wtf(TAG, "Package Manager Crash", e);
3823            }
3824            throw e;
3825        }
3826    }
3827
3828    static int[] appendInts(int[] cur, int[] add) {
3829        if (add == null) return cur;
3830        if (cur == null) return add;
3831        final int N = add.length;
3832        for (int i=0; i<N; i++) {
3833            cur = appendInt(cur, add[i]);
3834        }
3835        return cur;
3836    }
3837
3838    /**
3839     * Returns whether or not a full application can see an instant application.
3840     * <p>
3841     * Currently, there are three cases in which this can occur:
3842     * <ol>
3843     * <li>The calling application is a "special" process. Special processes
3844     *     are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li>
3845     * <li>The calling application has the permission
3846     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li>
3847     * <li>The calling application is the default launcher on the
3848     *     system partition.</li>
3849     * </ol>
3850     */
3851    private boolean canViewInstantApps(int callingUid, int userId) {
3852        if (callingUid < Process.FIRST_APPLICATION_UID) {
3853            return true;
3854        }
3855        if (mContext.checkCallingOrSelfPermission(
3856                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3857            return true;
3858        }
3859        if (mContext.checkCallingOrSelfPermission(
3860                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3861            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3862            if (homeComponent != null
3863                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3864                return true;
3865            }
3866        }
3867        return false;
3868    }
3869
3870    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3871        if (!sUserManager.exists(userId)) return null;
3872        if (ps == null) {
3873            return null;
3874        }
3875        final int callingUid = Binder.getCallingUid();
3876        // Filter out ephemeral app metadata:
3877        //   * The system/shell/root can see metadata for any app
3878        //   * An installed app can see metadata for 1) other installed apps
3879        //     and 2) ephemeral apps that have explicitly interacted with it
3880        //   * Ephemeral apps can only see their own data and exposed installed apps
3881        //   * Holding a signature permission allows seeing instant apps
3882        if (filterAppAccessLPr(ps, callingUid, userId)) {
3883            return null;
3884        }
3885
3886        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3887                && ps.isSystem()) {
3888            flags |= MATCH_ANY_USER;
3889        }
3890
3891        final PackageUserState state = ps.readUserState(userId);
3892        PackageParser.Package p = ps.pkg;
3893        if (p != null) {
3894            final PermissionsState permissionsState = ps.getPermissionsState();
3895
3896            // Compute GIDs only if requested
3897            final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3898                    ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3899            // Compute granted permissions only if package has requested permissions
3900            final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3901                    ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3902
3903            PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3904                    ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3905
3906            if (packageInfo == null) {
3907                return null;
3908            }
3909
3910            packageInfo.packageName = packageInfo.applicationInfo.packageName =
3911                    resolveExternalPackageNameLPr(p);
3912
3913            return packageInfo;
3914        } else if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 && state.isAvailable(flags)) {
3915            PackageInfo pi = new PackageInfo();
3916            pi.packageName = ps.name;
3917            pi.setLongVersionCode(ps.versionCode);
3918            pi.sharedUserId = (ps.sharedUser != null) ? ps.sharedUser.name : null;
3919            pi.firstInstallTime = ps.firstInstallTime;
3920            pi.lastUpdateTime = ps.lastUpdateTime;
3921
3922            ApplicationInfo ai = new ApplicationInfo();
3923            ai.packageName = ps.name;
3924            ai.uid = UserHandle.getUid(userId, ps.appId);
3925            ai.primaryCpuAbi = ps.primaryCpuAbiString;
3926            ai.secondaryCpuAbi = ps.secondaryCpuAbiString;
3927            ai.versionCode = ps.versionCode;
3928            ai.flags = ps.pkgFlags;
3929            ai.privateFlags = ps.pkgPrivateFlags;
3930            pi.applicationInfo = PackageParser.generateApplicationInfo(ai, flags, state, userId);
3931
3932            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "ps.pkg is n/a for ["
3933                    + ps.name + "]. Provides a minimum info.");
3934            return pi;
3935        } else {
3936            return null;
3937        }
3938    }
3939
3940    @Override
3941    public void checkPackageStartable(String packageName, int userId) {
3942        final int callingUid = Binder.getCallingUid();
3943        if (getInstantAppPackageName(callingUid) != null) {
3944            throw new SecurityException("Instant applications don't have access to this method");
3945        }
3946        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3947        synchronized (mPackages) {
3948            final PackageSetting ps = mSettings.mPackages.get(packageName);
3949            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3950                throw new SecurityException("Package " + packageName + " was not found!");
3951            }
3952
3953            if (!ps.getInstalled(userId)) {
3954                throw new SecurityException(
3955                        "Package " + packageName + " was not installed for user " + userId + "!");
3956            }
3957
3958            if (mSafeMode && !ps.isSystem()) {
3959                throw new SecurityException("Package " + packageName + " not a system app!");
3960            }
3961
3962            if (mFrozenPackages.contains(packageName)) {
3963                throw new SecurityException("Package " + packageName + " is currently frozen!");
3964            }
3965
3966            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3967                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3968            }
3969        }
3970    }
3971
3972    @Override
3973    public boolean isPackageAvailable(String packageName, int userId) {
3974        if (!sUserManager.exists(userId)) return false;
3975        final int callingUid = Binder.getCallingUid();
3976        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
3977                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3978        synchronized (mPackages) {
3979            PackageParser.Package p = mPackages.get(packageName);
3980            if (p != null) {
3981                final PackageSetting ps = (PackageSetting) p.mExtras;
3982                if (filterAppAccessLPr(ps, callingUid, userId)) {
3983                    return false;
3984                }
3985                if (ps != null) {
3986                    final PackageUserState state = ps.readUserState(userId);
3987                    if (state != null) {
3988                        return PackageParser.isAvailable(state);
3989                    }
3990                }
3991            }
3992        }
3993        return false;
3994    }
3995
3996    @Override
3997    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3998        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3999                flags, Binder.getCallingUid(), userId);
4000    }
4001
4002    @Override
4003    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
4004            int flags, int userId) {
4005        return getPackageInfoInternal(versionedPackage.getPackageName(),
4006                versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId);
4007    }
4008
4009    /**
4010     * Important: The provided filterCallingUid is used exclusively to filter out packages
4011     * that can be seen based on user state. It's typically the original caller uid prior
4012     * to clearing. Because it can only be provided by trusted code, it's value can be
4013     * trusted and will be used as-is; unlike userId which will be validated by this method.
4014     */
4015    private PackageInfo getPackageInfoInternal(String packageName, long versionCode,
4016            int flags, int filterCallingUid, int userId) {
4017        if (!sUserManager.exists(userId)) return null;
4018        flags = updateFlagsForPackage(flags, userId, packageName);
4019        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4020                false /* requireFullPermission */, false /* checkShell */, "get package info");
4021
4022        // reader
4023        synchronized (mPackages) {
4024            // Normalize package name to handle renamed packages and static libs
4025            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
4026
4027            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
4028            if (matchFactoryOnly) {
4029                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
4030                if (ps != null) {
4031                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4032                        return null;
4033                    }
4034                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4035                        return null;
4036                    }
4037                    return generatePackageInfo(ps, flags, userId);
4038                }
4039            }
4040
4041            PackageParser.Package p = mPackages.get(packageName);
4042            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
4043                return null;
4044            }
4045            if (DEBUG_PACKAGE_INFO)
4046                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
4047            if (p != null) {
4048                final PackageSetting ps = (PackageSetting) p.mExtras;
4049                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4050                    return null;
4051                }
4052                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
4053                    return null;
4054                }
4055                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
4056            }
4057            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
4058                final PackageSetting ps = mSettings.mPackages.get(packageName);
4059                if (ps == null) return null;
4060                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4061                    return null;
4062                }
4063                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4064                    return null;
4065                }
4066                return generatePackageInfo(ps, flags, userId);
4067            }
4068        }
4069        return null;
4070    }
4071
4072    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
4073        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
4074            return true;
4075        }
4076        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
4077            return true;
4078        }
4079        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4080            return true;
4081        }
4082        return false;
4083    }
4084
4085    private boolean isComponentVisibleToInstantApp(
4086            @Nullable ComponentName component, @ComponentType int type) {
4087        if (type == TYPE_ACTIVITY) {
4088            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4089            if (activity == null) {
4090                return false;
4091            }
4092            final boolean visibleToInstantApp =
4093                    (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
4094            final boolean explicitlyVisibleToInstantApp =
4095                    (activity.info.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
4096            return visibleToInstantApp && explicitlyVisibleToInstantApp;
4097        } else if (type == TYPE_RECEIVER) {
4098            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4099            if (activity == null) {
4100                return false;
4101            }
4102            final boolean visibleToInstantApp =
4103                    (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
4104            final boolean explicitlyVisibleToInstantApp =
4105                    (activity.info.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
4106            return visibleToInstantApp && !explicitlyVisibleToInstantApp;
4107        } else if (type == TYPE_SERVICE) {
4108            final PackageParser.Service service = mServices.mServices.get(component);
4109            return service != null
4110                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4111                    : false;
4112        } else if (type == TYPE_PROVIDER) {
4113            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4114            return provider != null
4115                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4116                    : false;
4117        } else if (type == TYPE_UNKNOWN) {
4118            return isComponentVisibleToInstantApp(component);
4119        }
4120        return false;
4121    }
4122
4123    /**
4124     * Returns whether or not access to the application should be filtered.
4125     * <p>
4126     * Access may be limited based upon whether the calling or target applications
4127     * are instant applications.
4128     *
4129     * @see #canAccessInstantApps(int)
4130     */
4131    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4132            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4133        // if we're in an isolated process, get the real calling UID
4134        if (Process.isIsolated(callingUid)) {
4135            callingUid = mIsolatedOwners.get(callingUid);
4136        }
4137        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4138        final boolean callerIsInstantApp = instantAppPkgName != null;
4139        if (ps == null) {
4140            if (callerIsInstantApp) {
4141                // pretend the application exists, but, needs to be filtered
4142                return true;
4143            }
4144            return false;
4145        }
4146        // if the target and caller are the same application, don't filter
4147        if (isCallerSameApp(ps.name, callingUid)) {
4148            return false;
4149        }
4150        if (callerIsInstantApp) {
4151            // both caller and target are both instant, but, different applications, filter
4152            if (ps.getInstantApp(userId)) {
4153                return true;
4154            }
4155            // request for a specific component; if it hasn't been explicitly exposed through
4156            // property or instrumentation target, filter
4157            if (component != null) {
4158                final PackageParser.Instrumentation instrumentation =
4159                        mInstrumentation.get(component);
4160                if (instrumentation != null
4161                        && isCallerSameApp(instrumentation.info.targetPackage, callingUid)) {
4162                    return false;
4163                }
4164                return !isComponentVisibleToInstantApp(component, componentType);
4165            }
4166            // request for application; if no components have been explicitly exposed, filter
4167            return !ps.pkg.visibleToInstantApps;
4168        }
4169        if (ps.getInstantApp(userId)) {
4170            // caller can see all components of all instant applications, don't filter
4171            if (canViewInstantApps(callingUid, userId)) {
4172                return false;
4173            }
4174            // request for a specific instant application component, filter
4175            if (component != null) {
4176                return true;
4177            }
4178            // request for an instant application; if the caller hasn't been granted access, filter
4179            return !mInstantAppRegistry.isInstantAccessGranted(
4180                    userId, UserHandle.getAppId(callingUid), ps.appId);
4181        }
4182        return false;
4183    }
4184
4185    /**
4186     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4187     */
4188    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4189        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4190    }
4191
4192    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4193            int flags) {
4194        // Callers can access only the libs they depend on, otherwise they need to explicitly
4195        // ask for the shared libraries given the caller is allowed to access all static libs.
4196        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4197            // System/shell/root get to see all static libs
4198            final int appId = UserHandle.getAppId(uid);
4199            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4200                    || appId == Process.ROOT_UID) {
4201                return false;
4202            }
4203        }
4204
4205        // No package means no static lib as it is always on internal storage
4206        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4207            return false;
4208        }
4209
4210        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4211                ps.pkg.staticSharedLibVersion);
4212        if (libEntry == null) {
4213            return false;
4214        }
4215
4216        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4217        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4218        if (uidPackageNames == null) {
4219            return true;
4220        }
4221
4222        for (String uidPackageName : uidPackageNames) {
4223            if (ps.name.equals(uidPackageName)) {
4224                return false;
4225            }
4226            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4227            if (uidPs != null) {
4228                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4229                        libEntry.info.getName());
4230                if (index < 0) {
4231                    continue;
4232                }
4233                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) {
4234                    return false;
4235                }
4236            }
4237        }
4238        return true;
4239    }
4240
4241    @Override
4242    public String[] currentToCanonicalPackageNames(String[] names) {
4243        final int callingUid = Binder.getCallingUid();
4244        if (getInstantAppPackageName(callingUid) != null) {
4245            return names;
4246        }
4247        final String[] out = new String[names.length];
4248        // reader
4249        synchronized (mPackages) {
4250            final int callingUserId = UserHandle.getUserId(callingUid);
4251            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4252            for (int i=names.length-1; i>=0; i--) {
4253                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4254                boolean translateName = false;
4255                if (ps != null && ps.realName != null) {
4256                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4257                    translateName = !targetIsInstantApp
4258                            || canViewInstantApps
4259                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4260                                    UserHandle.getAppId(callingUid), ps.appId);
4261                }
4262                out[i] = translateName ? ps.realName : names[i];
4263            }
4264        }
4265        return out;
4266    }
4267
4268    @Override
4269    public String[] canonicalToCurrentPackageNames(String[] names) {
4270        final int callingUid = Binder.getCallingUid();
4271        if (getInstantAppPackageName(callingUid) != null) {
4272            return names;
4273        }
4274        final String[] out = new String[names.length];
4275        // reader
4276        synchronized (mPackages) {
4277            final int callingUserId = UserHandle.getUserId(callingUid);
4278            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4279            for (int i=names.length-1; i>=0; i--) {
4280                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4281                boolean translateName = false;
4282                if (cur != null) {
4283                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4284                    final boolean targetIsInstantApp =
4285                            ps != null && ps.getInstantApp(callingUserId);
4286                    translateName = !targetIsInstantApp
4287                            || canViewInstantApps
4288                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4289                                    UserHandle.getAppId(callingUid), ps.appId);
4290                }
4291                out[i] = translateName ? cur : names[i];
4292            }
4293        }
4294        return out;
4295    }
4296
4297    @Override
4298    public int getPackageUid(String packageName, int flags, int userId) {
4299        if (!sUserManager.exists(userId)) return -1;
4300        final int callingUid = Binder.getCallingUid();
4301        flags = updateFlagsForPackage(flags, userId, packageName);
4302        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4303                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4304
4305        // reader
4306        synchronized (mPackages) {
4307            final PackageParser.Package p = mPackages.get(packageName);
4308            if (p != null && p.isMatch(flags)) {
4309                PackageSetting ps = (PackageSetting) p.mExtras;
4310                if (filterAppAccessLPr(ps, callingUid, userId)) {
4311                    return -1;
4312                }
4313                return UserHandle.getUid(userId, p.applicationInfo.uid);
4314            }
4315            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4316                final PackageSetting ps = mSettings.mPackages.get(packageName);
4317                if (ps != null && ps.isMatch(flags)
4318                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4319                    return UserHandle.getUid(userId, ps.appId);
4320                }
4321            }
4322        }
4323
4324        return -1;
4325    }
4326
4327    @Override
4328    public int[] getPackageGids(String packageName, int flags, int userId) {
4329        if (!sUserManager.exists(userId)) return null;
4330        final int callingUid = Binder.getCallingUid();
4331        flags = updateFlagsForPackage(flags, userId, packageName);
4332        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4333                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4334
4335        // reader
4336        synchronized (mPackages) {
4337            final PackageParser.Package p = mPackages.get(packageName);
4338            if (p != null && p.isMatch(flags)) {
4339                PackageSetting ps = (PackageSetting) p.mExtras;
4340                if (filterAppAccessLPr(ps, callingUid, userId)) {
4341                    return null;
4342                }
4343                // TODO: Shouldn't this be checking for package installed state for userId and
4344                // return null?
4345                return ps.getPermissionsState().computeGids(userId);
4346            }
4347            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4348                final PackageSetting ps = mSettings.mPackages.get(packageName);
4349                if (ps != null && ps.isMatch(flags)
4350                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4351                    return ps.getPermissionsState().computeGids(userId);
4352                }
4353            }
4354        }
4355
4356        return null;
4357    }
4358
4359    @Override
4360    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4361        return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4362    }
4363
4364    @Override
4365    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4366            int flags) {
4367        final List<PermissionInfo> permissionList =
4368                mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid());
4369        return (permissionList == null) ? null : new ParceledListSlice<>(permissionList);
4370    }
4371
4372    @Override
4373    public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) {
4374        return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid());
4375    }
4376
4377    @Override
4378    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4379        final List<PermissionGroupInfo> permissionList =
4380                mPermissionManager.getAllPermissionGroups(flags, getCallingUid());
4381        return (permissionList == null)
4382                ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList);
4383    }
4384
4385    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4386            int filterCallingUid, int userId) {
4387        if (!sUserManager.exists(userId)) return null;
4388        PackageSetting ps = mSettings.mPackages.get(packageName);
4389        if (ps != null) {
4390            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4391                return null;
4392            }
4393            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4394                return null;
4395            }
4396            if (ps.pkg == null) {
4397                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4398                if (pInfo != null) {
4399                    return pInfo.applicationInfo;
4400                }
4401                return null;
4402            }
4403            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4404                    ps.readUserState(userId), userId);
4405            if (ai != null) {
4406                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4407            }
4408            return ai;
4409        }
4410        return null;
4411    }
4412
4413    @Override
4414    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4415        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4416    }
4417
4418    /**
4419     * Important: The provided filterCallingUid is used exclusively to filter out applications
4420     * that can be seen based on user state. It's typically the original caller uid prior
4421     * to clearing. Because it can only be provided by trusted code, it's value can be
4422     * trusted and will be used as-is; unlike userId which will be validated by this method.
4423     */
4424    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4425            int filterCallingUid, int userId) {
4426        if (!sUserManager.exists(userId)) return null;
4427        flags = updateFlagsForApplication(flags, userId, packageName);
4428        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4429                false /* requireFullPermission */, false /* checkShell */, "get application info");
4430
4431        // writer
4432        synchronized (mPackages) {
4433            // Normalize package name to handle renamed packages and static libs
4434            packageName = resolveInternalPackageNameLPr(packageName,
4435                    PackageManager.VERSION_CODE_HIGHEST);
4436
4437            PackageParser.Package p = mPackages.get(packageName);
4438            if (DEBUG_PACKAGE_INFO) Log.v(
4439                    TAG, "getApplicationInfo " + packageName
4440                    + ": " + p);
4441            if (p != null) {
4442                PackageSetting ps = mSettings.mPackages.get(packageName);
4443                if (ps == null) return null;
4444                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4445                    return null;
4446                }
4447                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4448                    return null;
4449                }
4450                // Note: isEnabledLP() does not apply here - always return info
4451                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4452                        p, flags, ps.readUserState(userId), userId);
4453                if (ai != null) {
4454                    ai.packageName = resolveExternalPackageNameLPr(p);
4455                }
4456                return ai;
4457            }
4458            if ("android".equals(packageName)||"system".equals(packageName)) {
4459                return mAndroidApplication;
4460            }
4461            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4462                // Already generates the external package name
4463                return generateApplicationInfoFromSettingsLPw(packageName,
4464                        flags, filterCallingUid, userId);
4465            }
4466        }
4467        return null;
4468    }
4469
4470    private String normalizePackageNameLPr(String packageName) {
4471        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4472        return normalizedPackageName != null ? normalizedPackageName : packageName;
4473    }
4474
4475    @Override
4476    public void deletePreloadsFileCache() {
4477        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4478            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4479        }
4480        File dir = Environment.getDataPreloadsFileCacheDirectory();
4481        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4482        FileUtils.deleteContents(dir);
4483    }
4484
4485    @Override
4486    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4487            final int storageFlags, final IPackageDataObserver observer) {
4488        mContext.enforceCallingOrSelfPermission(
4489                android.Manifest.permission.CLEAR_APP_CACHE, null);
4490        mHandler.post(() -> {
4491            boolean success = false;
4492            try {
4493                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4494                success = true;
4495            } catch (IOException e) {
4496                Slog.w(TAG, e);
4497            }
4498            if (observer != null) {
4499                try {
4500                    observer.onRemoveCompleted(null, success);
4501                } catch (RemoteException e) {
4502                    Slog.w(TAG, e);
4503                }
4504            }
4505        });
4506    }
4507
4508    @Override
4509    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4510            final int storageFlags, final IntentSender pi) {
4511        mContext.enforceCallingOrSelfPermission(
4512                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4513        mHandler.post(() -> {
4514            boolean success = false;
4515            try {
4516                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4517                success = true;
4518            } catch (IOException e) {
4519                Slog.w(TAG, e);
4520            }
4521            if (pi != null) {
4522                try {
4523                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4524                } catch (SendIntentException e) {
4525                    Slog.w(TAG, e);
4526                }
4527            }
4528        });
4529    }
4530
4531    /**
4532     * Blocking call to clear various types of cached data across the system
4533     * until the requested bytes are available.
4534     */
4535    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4536        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4537        final File file = storage.findPathForUuid(volumeUuid);
4538        if (file.getUsableSpace() >= bytes) return;
4539
4540        if (ENABLE_FREE_CACHE_V2) {
4541            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4542                    volumeUuid);
4543            final boolean aggressive = (storageFlags
4544                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4545            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4546
4547            // 1. Pre-flight to determine if we have any chance to succeed
4548            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4549            if (internalVolume && (aggressive || SystemProperties
4550                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4551                deletePreloadsFileCache();
4552                if (file.getUsableSpace() >= bytes) return;
4553            }
4554
4555            // 3. Consider parsed APK data (aggressive only)
4556            if (internalVolume && aggressive) {
4557                FileUtils.deleteContents(mCacheDir);
4558                if (file.getUsableSpace() >= bytes) return;
4559            }
4560
4561            // 4. Consider cached app data (above quotas)
4562            try {
4563                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4564                        Installer.FLAG_FREE_CACHE_V2);
4565            } catch (InstallerException ignored) {
4566            }
4567            if (file.getUsableSpace() >= bytes) return;
4568
4569            // 5. Consider shared libraries with refcount=0 and age>min cache period
4570            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4571                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4572                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4573                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4574                return;
4575            }
4576
4577            // 6. Consider dexopt output (aggressive only)
4578            // TODO: Implement
4579
4580            // 7. Consider installed instant apps unused longer than min cache period
4581            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4582                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4583                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4584                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4585                return;
4586            }
4587
4588            // 8. Consider cached app data (below quotas)
4589            try {
4590                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4591                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4592            } catch (InstallerException ignored) {
4593            }
4594            if (file.getUsableSpace() >= bytes) return;
4595
4596            // 9. Consider DropBox entries
4597            // TODO: Implement
4598
4599            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4600            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4601                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4602                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4603                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4604                return;
4605            }
4606        } else {
4607            try {
4608                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4609            } catch (InstallerException ignored) {
4610            }
4611            if (file.getUsableSpace() >= bytes) return;
4612        }
4613
4614        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4615    }
4616
4617    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4618            throws IOException {
4619        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4620        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4621
4622        List<VersionedPackage> packagesToDelete = null;
4623        final long now = System.currentTimeMillis();
4624
4625        synchronized (mPackages) {
4626            final int[] allUsers = sUserManager.getUserIds();
4627            final int libCount = mSharedLibraries.size();
4628            for (int i = 0; i < libCount; i++) {
4629                final LongSparseArray<SharedLibraryEntry> versionedLib
4630                        = mSharedLibraries.valueAt(i);
4631                if (versionedLib == null) {
4632                    continue;
4633                }
4634                final int versionCount = versionedLib.size();
4635                for (int j = 0; j < versionCount; j++) {
4636                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4637                    // Skip packages that are not static shared libs.
4638                    if (!libInfo.isStatic()) {
4639                        break;
4640                    }
4641                    // Important: We skip static shared libs used for some user since
4642                    // in such a case we need to keep the APK on the device. The check for
4643                    // a lib being used for any user is performed by the uninstall call.
4644                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4645                    // Resolve the package name - we use synthetic package names internally
4646                    final String internalPackageName = resolveInternalPackageNameLPr(
4647                            declaringPackage.getPackageName(),
4648                            declaringPackage.getLongVersionCode());
4649                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4650                    // Skip unused static shared libs cached less than the min period
4651                    // to prevent pruning a lib needed by a subsequently installed package.
4652                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4653                        continue;
4654                    }
4655                    if (packagesToDelete == null) {
4656                        packagesToDelete = new ArrayList<>();
4657                    }
4658                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4659                            declaringPackage.getLongVersionCode()));
4660                }
4661            }
4662        }
4663
4664        if (packagesToDelete != null) {
4665            final int packageCount = packagesToDelete.size();
4666            for (int i = 0; i < packageCount; i++) {
4667                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4668                // Delete the package synchronously (will fail of the lib used for any user).
4669                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(),
4670                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4671                                == PackageManager.DELETE_SUCCEEDED) {
4672                    if (volume.getUsableSpace() >= neededSpace) {
4673                        return true;
4674                    }
4675                }
4676            }
4677        }
4678
4679        return false;
4680    }
4681
4682    /**
4683     * Update given flags based on encryption status of current user.
4684     */
4685    private int updateFlags(int flags, int userId) {
4686        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4687                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4688            // Caller expressed an explicit opinion about what encryption
4689            // aware/unaware components they want to see, so fall through and
4690            // give them what they want
4691        } else {
4692            // Caller expressed no opinion, so match based on user state
4693            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4694                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4695            } else {
4696                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4697            }
4698        }
4699        return flags;
4700    }
4701
4702    private UserManagerInternal getUserManagerInternal() {
4703        if (mUserManagerInternal == null) {
4704            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4705        }
4706        return mUserManagerInternal;
4707    }
4708
4709    private ActivityManagerInternal getActivityManagerInternal() {
4710        if (mActivityManagerInternal == null) {
4711            mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
4712        }
4713        return mActivityManagerInternal;
4714    }
4715
4716
4717    private DeviceIdleController.LocalService getDeviceIdleController() {
4718        if (mDeviceIdleController == null) {
4719            mDeviceIdleController =
4720                    LocalServices.getService(DeviceIdleController.LocalService.class);
4721        }
4722        return mDeviceIdleController;
4723    }
4724
4725    /**
4726     * Update given flags when being used to request {@link PackageInfo}.
4727     */
4728    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4729        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4730        boolean triaged = true;
4731        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4732                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4733            // Caller is asking for component details, so they'd better be
4734            // asking for specific encryption matching behavior, or be triaged
4735            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4736                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4737                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4738                triaged = false;
4739            }
4740        }
4741        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4742                | PackageManager.MATCH_SYSTEM_ONLY
4743                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4744            triaged = false;
4745        }
4746        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4747            mPermissionManager.enforceCrossUserPermission(
4748                    Binder.getCallingUid(), userId, false, false,
4749                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4750                    + Debug.getCallers(5));
4751        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4752                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4753            // If the caller wants all packages and has a restricted profile associated with it,
4754            // then match all users. This is to make sure that launchers that need to access work
4755            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4756            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4757            flags |= PackageManager.MATCH_ANY_USER;
4758        }
4759        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4760            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4761                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4762        }
4763        return updateFlags(flags, userId);
4764    }
4765
4766    /**
4767     * Update given flags when being used to request {@link ApplicationInfo}.
4768     */
4769    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4770        return updateFlagsForPackage(flags, userId, cookie);
4771    }
4772
4773    /**
4774     * Update given flags when being used to request {@link ComponentInfo}.
4775     */
4776    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4777        if (cookie instanceof Intent) {
4778            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4779                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4780            }
4781        }
4782
4783        boolean triaged = true;
4784        // Caller is asking for component details, so they'd better be
4785        // asking for specific encryption matching behavior, or be triaged
4786        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4787                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4788                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4789            triaged = false;
4790        }
4791        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4792            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4793                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4794        }
4795
4796        return updateFlags(flags, userId);
4797    }
4798
4799    /**
4800     * Update given intent when being used to request {@link ResolveInfo}.
4801     */
4802    private Intent updateIntentForResolve(Intent intent) {
4803        if (intent.getSelector() != null) {
4804            intent = intent.getSelector();
4805        }
4806        if (DEBUG_PREFERRED) {
4807            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4808        }
4809        return intent;
4810    }
4811
4812    /**
4813     * Update given flags when being used to request {@link ResolveInfo}.
4814     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4815     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4816     * flag set. However, this flag is only honoured in three circumstances:
4817     * <ul>
4818     * <li>when called from a system process</li>
4819     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4820     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4821     * action and a {@code android.intent.category.BROWSABLE} category</li>
4822     * </ul>
4823     */
4824    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4825        return updateFlagsForResolve(flags, userId, intent, callingUid,
4826                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4827    }
4828    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4829            boolean wantInstantApps) {
4830        return updateFlagsForResolve(flags, userId, intent, callingUid,
4831                wantInstantApps, false /*onlyExposedExplicitly*/);
4832    }
4833    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4834            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4835        // Safe mode means we shouldn't match any third-party components
4836        if (mSafeMode) {
4837            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4838        }
4839        if (getInstantAppPackageName(callingUid) != null) {
4840            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4841            if (onlyExposedExplicitly) {
4842                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4843            }
4844            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4845            flags |= PackageManager.MATCH_INSTANT;
4846        } else {
4847            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4848            final boolean allowMatchInstant = wantInstantApps
4849                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4850            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4851                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4852            if (!allowMatchInstant) {
4853                flags &= ~PackageManager.MATCH_INSTANT;
4854            }
4855        }
4856        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4857    }
4858
4859    @Override
4860    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4861        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4862    }
4863
4864    /**
4865     * Important: The provided filterCallingUid is used exclusively to filter out activities
4866     * that can be seen based on user state. It's typically the original caller uid prior
4867     * to clearing. Because it can only be provided by trusted code, it's value can be
4868     * trusted and will be used as-is; unlike userId which will be validated by this method.
4869     */
4870    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4871            int filterCallingUid, int userId) {
4872        if (!sUserManager.exists(userId)) return null;
4873        flags = updateFlagsForComponent(flags, userId, component);
4874
4875        if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) {
4876            mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4877                    false /* requireFullPermission */, false /* checkShell */, "get activity info");
4878        }
4879
4880        synchronized (mPackages) {
4881            PackageParser.Activity a = mActivities.mActivities.get(component);
4882
4883            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4884            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4885                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4886                if (ps == null) return null;
4887                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4888                    return null;
4889                }
4890                return PackageParser.generateActivityInfo(
4891                        a, flags, ps.readUserState(userId), userId);
4892            }
4893            if (mResolveComponentName.equals(component)) {
4894                return PackageParser.generateActivityInfo(
4895                        mResolveActivity, flags, new PackageUserState(), userId);
4896            }
4897        }
4898        return null;
4899    }
4900
4901    private boolean isRecentsAccessingChildProfiles(int callingUid, int targetUserId) {
4902        if (!getActivityManagerInternal().isCallerRecents(callingUid)) {
4903            return false;
4904        }
4905        final long token = Binder.clearCallingIdentity();
4906        try {
4907            final int callingUserId = UserHandle.getUserId(callingUid);
4908            if (ActivityManager.getCurrentUser() != callingUserId) {
4909                return false;
4910            }
4911            return sUserManager.isSameProfileGroup(callingUserId, targetUserId);
4912        } finally {
4913            Binder.restoreCallingIdentity(token);
4914        }
4915    }
4916
4917    @Override
4918    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4919            String resolvedType) {
4920        synchronized (mPackages) {
4921            if (component.equals(mResolveComponentName)) {
4922                // The resolver supports EVERYTHING!
4923                return true;
4924            }
4925            final int callingUid = Binder.getCallingUid();
4926            final int callingUserId = UserHandle.getUserId(callingUid);
4927            PackageParser.Activity a = mActivities.mActivities.get(component);
4928            if (a == null) {
4929                return false;
4930            }
4931            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4932            if (ps == null) {
4933                return false;
4934            }
4935            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4936                return false;
4937            }
4938            for (int i=0; i<a.intents.size(); i++) {
4939                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4940                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4941                    return true;
4942                }
4943            }
4944            return false;
4945        }
4946    }
4947
4948    @Override
4949    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4950        if (!sUserManager.exists(userId)) return null;
4951        final int callingUid = Binder.getCallingUid();
4952        flags = updateFlagsForComponent(flags, userId, component);
4953        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4954                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4955        synchronized (mPackages) {
4956            PackageParser.Activity a = mReceivers.mActivities.get(component);
4957            if (DEBUG_PACKAGE_INFO) Log.v(
4958                TAG, "getReceiverInfo " + component + ": " + a);
4959            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4960                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4961                if (ps == null) return null;
4962                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4963                    return null;
4964                }
4965                return PackageParser.generateActivityInfo(
4966                        a, flags, ps.readUserState(userId), userId);
4967            }
4968        }
4969        return null;
4970    }
4971
4972    @Override
4973    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4974            int flags, int userId) {
4975        if (!sUserManager.exists(userId)) return null;
4976        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4977        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4978            return null;
4979        }
4980
4981        flags = updateFlagsForPackage(flags, userId, null);
4982
4983        final boolean canSeeStaticLibraries =
4984                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4985                        == PERMISSION_GRANTED
4986                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4987                        == PERMISSION_GRANTED
4988                || canRequestPackageInstallsInternal(packageName,
4989                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4990                        false  /* throwIfPermNotDeclared*/)
4991                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4992                        == PERMISSION_GRANTED;
4993
4994        synchronized (mPackages) {
4995            List<SharedLibraryInfo> result = null;
4996
4997            final int libCount = mSharedLibraries.size();
4998            for (int i = 0; i < libCount; i++) {
4999                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5000                if (versionedLib == null) {
5001                    continue;
5002                }
5003
5004                final int versionCount = versionedLib.size();
5005                for (int j = 0; j < versionCount; j++) {
5006                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
5007                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
5008                        break;
5009                    }
5010                    final long identity = Binder.clearCallingIdentity();
5011                    try {
5012                        PackageInfo packageInfo = getPackageInfoVersioned(
5013                                libInfo.getDeclaringPackage(), flags
5014                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
5015                        if (packageInfo == null) {
5016                            continue;
5017                        }
5018                    } finally {
5019                        Binder.restoreCallingIdentity(identity);
5020                    }
5021
5022                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
5023                            libInfo.getLongVersion(), libInfo.getType(),
5024                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
5025                            flags, userId));
5026
5027                    if (result == null) {
5028                        result = new ArrayList<>();
5029                    }
5030                    result.add(resLibInfo);
5031                }
5032            }
5033
5034            return result != null ? new ParceledListSlice<>(result) : null;
5035        }
5036    }
5037
5038    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
5039            SharedLibraryInfo libInfo, int flags, int userId) {
5040        List<VersionedPackage> versionedPackages = null;
5041        final int packageCount = mSettings.mPackages.size();
5042        for (int i = 0; i < packageCount; i++) {
5043            PackageSetting ps = mSettings.mPackages.valueAt(i);
5044
5045            if (ps == null) {
5046                continue;
5047            }
5048
5049            if (!ps.getUserState().get(userId).isAvailable(flags)) {
5050                continue;
5051            }
5052
5053            final String libName = libInfo.getName();
5054            if (libInfo.isStatic()) {
5055                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
5056                if (libIdx < 0) {
5057                    continue;
5058                }
5059                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) {
5060                    continue;
5061                }
5062                if (versionedPackages == null) {
5063                    versionedPackages = new ArrayList<>();
5064                }
5065                // If the dependent is a static shared lib, use the public package name
5066                String dependentPackageName = ps.name;
5067                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5068                    dependentPackageName = ps.pkg.manifestPackageName;
5069                }
5070                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5071            } else if (ps.pkg != null) {
5072                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5073                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5074                    if (versionedPackages == null) {
5075                        versionedPackages = new ArrayList<>();
5076                    }
5077                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5078                }
5079            }
5080        }
5081
5082        return versionedPackages;
5083    }
5084
5085    @Override
5086    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5087        if (!sUserManager.exists(userId)) return null;
5088        final int callingUid = Binder.getCallingUid();
5089        flags = updateFlagsForComponent(flags, userId, component);
5090        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5091                false /* requireFullPermission */, false /* checkShell */, "get service info");
5092        synchronized (mPackages) {
5093            PackageParser.Service s = mServices.mServices.get(component);
5094            if (DEBUG_PACKAGE_INFO) Log.v(
5095                TAG, "getServiceInfo " + component + ": " + s);
5096            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5097                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5098                if (ps == null) return null;
5099                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5100                    return null;
5101                }
5102                return PackageParser.generateServiceInfo(
5103                        s, flags, ps.readUserState(userId), userId);
5104            }
5105        }
5106        return null;
5107    }
5108
5109    @Override
5110    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5111        if (!sUserManager.exists(userId)) return null;
5112        final int callingUid = Binder.getCallingUid();
5113        flags = updateFlagsForComponent(flags, userId, component);
5114        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5115                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5116        synchronized (mPackages) {
5117            PackageParser.Provider p = mProviders.mProviders.get(component);
5118            if (DEBUG_PACKAGE_INFO) Log.v(
5119                TAG, "getProviderInfo " + component + ": " + p);
5120            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5121                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5122                if (ps == null) return null;
5123                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5124                    return null;
5125                }
5126                return PackageParser.generateProviderInfo(
5127                        p, flags, ps.readUserState(userId), userId);
5128            }
5129        }
5130        return null;
5131    }
5132
5133    @Override
5134    public String[] getSystemSharedLibraryNames() {
5135        // allow instant applications
5136        synchronized (mPackages) {
5137            Set<String> libs = null;
5138            final int libCount = mSharedLibraries.size();
5139            for (int i = 0; i < libCount; i++) {
5140                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5141                if (versionedLib == null) {
5142                    continue;
5143                }
5144                final int versionCount = versionedLib.size();
5145                for (int j = 0; j < versionCount; j++) {
5146                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5147                    if (!libEntry.info.isStatic()) {
5148                        if (libs == null) {
5149                            libs = new ArraySet<>();
5150                        }
5151                        libs.add(libEntry.info.getName());
5152                        break;
5153                    }
5154                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5155                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5156                            UserHandle.getUserId(Binder.getCallingUid()),
5157                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5158                        if (libs == null) {
5159                            libs = new ArraySet<>();
5160                        }
5161                        libs.add(libEntry.info.getName());
5162                        break;
5163                    }
5164                }
5165            }
5166
5167            if (libs != null) {
5168                String[] libsArray = new String[libs.size()];
5169                libs.toArray(libsArray);
5170                return libsArray;
5171            }
5172
5173            return null;
5174        }
5175    }
5176
5177    @Override
5178    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5179        // allow instant applications
5180        synchronized (mPackages) {
5181            return mServicesSystemSharedLibraryPackageName;
5182        }
5183    }
5184
5185    @Override
5186    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5187        // allow instant applications
5188        synchronized (mPackages) {
5189            return mSharedSystemSharedLibraryPackageName;
5190        }
5191    }
5192
5193    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5194        for (int i = userList.length - 1; i >= 0; --i) {
5195            final int userId = userList[i];
5196            // don't add instant app to the list of updates
5197            if (pkgSetting.getInstantApp(userId)) {
5198                continue;
5199            }
5200            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5201            if (changedPackages == null) {
5202                changedPackages = new SparseArray<>();
5203                mChangedPackages.put(userId, changedPackages);
5204            }
5205            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5206            if (sequenceNumbers == null) {
5207                sequenceNumbers = new HashMap<>();
5208                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5209            }
5210            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5211            if (sequenceNumber != null) {
5212                changedPackages.remove(sequenceNumber);
5213            }
5214            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5215            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5216        }
5217        mChangedPackagesSequenceNumber++;
5218    }
5219
5220    @Override
5221    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5222        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5223            return null;
5224        }
5225        synchronized (mPackages) {
5226            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5227                return null;
5228            }
5229            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5230            if (changedPackages == null) {
5231                return null;
5232            }
5233            final List<String> packageNames =
5234                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5235            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5236                final String packageName = changedPackages.get(i);
5237                if (packageName != null) {
5238                    packageNames.add(packageName);
5239                }
5240            }
5241            return packageNames.isEmpty()
5242                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5243        }
5244    }
5245
5246    @Override
5247    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5248        // allow instant applications
5249        ArrayList<FeatureInfo> res;
5250        synchronized (mAvailableFeatures) {
5251            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5252            res.addAll(mAvailableFeatures.values());
5253        }
5254        final FeatureInfo fi = new FeatureInfo();
5255        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5256                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5257        res.add(fi);
5258
5259        return new ParceledListSlice<>(res);
5260    }
5261
5262    @Override
5263    public boolean hasSystemFeature(String name, int version) {
5264        // allow instant applications
5265        synchronized (mAvailableFeatures) {
5266            final FeatureInfo feat = mAvailableFeatures.get(name);
5267            if (feat == null) {
5268                return false;
5269            } else {
5270                return feat.version >= version;
5271            }
5272        }
5273    }
5274
5275    @Override
5276    public int checkPermission(String permName, String pkgName, int userId) {
5277        return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
5278    }
5279
5280    @Override
5281    public int checkUidPermission(String permName, int uid) {
5282        synchronized (mPackages) {
5283            final String[] packageNames = getPackagesForUid(uid);
5284            final PackageParser.Package pkg = (packageNames != null && packageNames.length > 0)
5285                    ? mPackages.get(packageNames[0])
5286                    : null;
5287            return mPermissionManager.checkUidPermission(permName, pkg, uid, getCallingUid());
5288        }
5289    }
5290
5291    @Override
5292    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5293        if (UserHandle.getCallingUserId() != userId) {
5294            mContext.enforceCallingPermission(
5295                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5296                    "isPermissionRevokedByPolicy for user " + userId);
5297        }
5298
5299        if (checkPermission(permission, packageName, userId)
5300                == PackageManager.PERMISSION_GRANTED) {
5301            return false;
5302        }
5303
5304        final int callingUid = Binder.getCallingUid();
5305        if (getInstantAppPackageName(callingUid) != null) {
5306            if (!isCallerSameApp(packageName, callingUid)) {
5307                return false;
5308            }
5309        } else {
5310            if (isInstantApp(packageName, userId)) {
5311                return false;
5312            }
5313        }
5314
5315        final long identity = Binder.clearCallingIdentity();
5316        try {
5317            final int flags = getPermissionFlags(permission, packageName, userId);
5318            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5319        } finally {
5320            Binder.restoreCallingIdentity(identity);
5321        }
5322    }
5323
5324    @Override
5325    public String getPermissionControllerPackageName() {
5326        synchronized (mPackages) {
5327            return mRequiredInstallerPackage;
5328        }
5329    }
5330
5331    private boolean addDynamicPermission(PermissionInfo info, final boolean async) {
5332        return mPermissionManager.addDynamicPermission(
5333                info, async, getCallingUid(), new PermissionCallback() {
5334                    @Override
5335                    public void onPermissionChanged() {
5336                        if (!async) {
5337                            mSettings.writeLPr();
5338                        } else {
5339                            scheduleWriteSettingsLocked();
5340                        }
5341                    }
5342                });
5343    }
5344
5345    @Override
5346    public boolean addPermission(PermissionInfo info) {
5347        synchronized (mPackages) {
5348            return addDynamicPermission(info, false);
5349        }
5350    }
5351
5352    @Override
5353    public boolean addPermissionAsync(PermissionInfo info) {
5354        synchronized (mPackages) {
5355            return addDynamicPermission(info, true);
5356        }
5357    }
5358
5359    @Override
5360    public void removePermission(String permName) {
5361        mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback);
5362    }
5363
5364    @Override
5365    public void grantRuntimePermission(String packageName, String permName, final int userId) {
5366        mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
5367                getCallingUid(), userId, mPermissionCallback);
5368    }
5369
5370    @Override
5371    public void revokeRuntimePermission(String packageName, String permName, int userId) {
5372        mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
5373                getCallingUid(), userId, mPermissionCallback);
5374    }
5375
5376    @Override
5377    public void resetRuntimePermissions() {
5378        mContext.enforceCallingOrSelfPermission(
5379                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5380                "revokeRuntimePermission");
5381
5382        int callingUid = Binder.getCallingUid();
5383        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5384            mContext.enforceCallingOrSelfPermission(
5385                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5386                    "resetRuntimePermissions");
5387        }
5388
5389        synchronized (mPackages) {
5390            mPermissionManager.updateAllPermissions(
5391                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
5392                    mPermissionCallback);
5393            for (int userId : UserManagerService.getInstance().getUserIds()) {
5394                final int packageCount = mPackages.size();
5395                for (int i = 0; i < packageCount; i++) {
5396                    PackageParser.Package pkg = mPackages.valueAt(i);
5397                    if (!(pkg.mExtras instanceof PackageSetting)) {
5398                        continue;
5399                    }
5400                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5401                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5402                }
5403            }
5404        }
5405    }
5406
5407    @Override
5408    public int getPermissionFlags(String permName, String packageName, int userId) {
5409        return mPermissionManager.getPermissionFlags(
5410                permName, packageName, getCallingUid(), userId);
5411    }
5412
5413    @Override
5414    public void updatePermissionFlags(String permName, String packageName, int flagMask,
5415            int flagValues, int userId) {
5416        mPermissionManager.updatePermissionFlags(
5417                permName, packageName, flagMask, flagValues, getCallingUid(), userId,
5418                mPermissionCallback);
5419    }
5420
5421    /**
5422     * Update the permission flags for all packages and runtime permissions of a user in order
5423     * to allow device or profile owner to remove POLICY_FIXED.
5424     */
5425    @Override
5426    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5427        synchronized (mPackages) {
5428            final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5429                    flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5430                    mPermissionCallback);
5431            if (changed) {
5432                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5433            }
5434        }
5435    }
5436
5437    @Override
5438    public boolean shouldShowRequestPermissionRationale(String permissionName,
5439            String packageName, int userId) {
5440        if (UserHandle.getCallingUserId() != userId) {
5441            mContext.enforceCallingPermission(
5442                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5443                    "canShowRequestPermissionRationale for user " + userId);
5444        }
5445
5446        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5447        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5448            return false;
5449        }
5450
5451        if (checkPermission(permissionName, packageName, userId)
5452                == PackageManager.PERMISSION_GRANTED) {
5453            return false;
5454        }
5455
5456        final int flags;
5457
5458        final long identity = Binder.clearCallingIdentity();
5459        try {
5460            flags = getPermissionFlags(permissionName,
5461                    packageName, userId);
5462        } finally {
5463            Binder.restoreCallingIdentity(identity);
5464        }
5465
5466        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5467                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5468                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5469
5470        if ((flags & fixedFlags) != 0) {
5471            return false;
5472        }
5473
5474        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5475    }
5476
5477    @Override
5478    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5479        mContext.enforceCallingOrSelfPermission(
5480                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5481                "addOnPermissionsChangeListener");
5482
5483        synchronized (mPackages) {
5484            mOnPermissionChangeListeners.addListenerLocked(listener);
5485        }
5486    }
5487
5488    @Override
5489    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5490        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5491            throw new SecurityException("Instant applications don't have access to this method");
5492        }
5493        synchronized (mPackages) {
5494            mOnPermissionChangeListeners.removeListenerLocked(listener);
5495        }
5496    }
5497
5498    @Override
5499    public boolean isProtectedBroadcast(String actionName) {
5500        // allow instant applications
5501        synchronized (mProtectedBroadcasts) {
5502            if (mProtectedBroadcasts.contains(actionName)) {
5503                return true;
5504            } else if (actionName != null) {
5505                // TODO: remove these terrible hacks
5506                if (actionName.startsWith("android.net.netmon.lingerExpired")
5507                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5508                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5509                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5510                    return true;
5511                }
5512            }
5513        }
5514        return false;
5515    }
5516
5517    @Override
5518    public int checkSignatures(String pkg1, String pkg2) {
5519        synchronized (mPackages) {
5520            final PackageParser.Package p1 = mPackages.get(pkg1);
5521            final PackageParser.Package p2 = mPackages.get(pkg2);
5522            if (p1 == null || p1.mExtras == null
5523                    || p2 == null || p2.mExtras == null) {
5524                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5525            }
5526            final int callingUid = Binder.getCallingUid();
5527            final int callingUserId = UserHandle.getUserId(callingUid);
5528            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5529            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5530            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5531                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5532                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5533            }
5534            return compareSignatures(p1.mSigningDetails.signatures, p2.mSigningDetails.signatures);
5535        }
5536    }
5537
5538    @Override
5539    public int checkUidSignatures(int uid1, int uid2) {
5540        final int callingUid = Binder.getCallingUid();
5541        final int callingUserId = UserHandle.getUserId(callingUid);
5542        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5543        // Map to base uids.
5544        uid1 = UserHandle.getAppId(uid1);
5545        uid2 = UserHandle.getAppId(uid2);
5546        // reader
5547        synchronized (mPackages) {
5548            Signature[] s1;
5549            Signature[] s2;
5550            Object obj = mSettings.getUserIdLPr(uid1);
5551            if (obj != null) {
5552                if (obj instanceof SharedUserSetting) {
5553                    if (isCallerInstantApp) {
5554                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5555                    }
5556                    s1 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5557                } else if (obj instanceof PackageSetting) {
5558                    final PackageSetting ps = (PackageSetting) obj;
5559                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5560                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5561                    }
5562                    s1 = ps.signatures.mSigningDetails.signatures;
5563                } else {
5564                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5565                }
5566            } else {
5567                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5568            }
5569            obj = mSettings.getUserIdLPr(uid2);
5570            if (obj != null) {
5571                if (obj instanceof SharedUserSetting) {
5572                    if (isCallerInstantApp) {
5573                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5574                    }
5575                    s2 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5576                } else if (obj instanceof PackageSetting) {
5577                    final PackageSetting ps = (PackageSetting) obj;
5578                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5579                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5580                    }
5581                    s2 = ps.signatures.mSigningDetails.signatures;
5582                } else {
5583                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5584                }
5585            } else {
5586                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5587            }
5588            return compareSignatures(s1, s2);
5589        }
5590    }
5591
5592    @Override
5593    public boolean hasSigningCertificate(
5594            String packageName, byte[] certificate, @PackageManager.CertificateInputType int type) {
5595
5596        synchronized (mPackages) {
5597            final PackageParser.Package p = mPackages.get(packageName);
5598            if (p == null || p.mExtras == null) {
5599                return false;
5600            }
5601            final int callingUid = Binder.getCallingUid();
5602            final int callingUserId = UserHandle.getUserId(callingUid);
5603            final PackageSetting ps = (PackageSetting) p.mExtras;
5604            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5605                return false;
5606            }
5607            switch (type) {
5608                case CERT_INPUT_RAW_X509:
5609                    return p.mSigningDetails.hasCertificate(certificate);
5610                case CERT_INPUT_SHA256:
5611                    return p.mSigningDetails.hasSha256Certificate(certificate);
5612                default:
5613                    return false;
5614            }
5615        }
5616    }
5617
5618    @Override
5619    public boolean hasUidSigningCertificate(
5620            int uid, byte[] certificate, @PackageManager.CertificateInputType int type) {
5621        final int callingUid = Binder.getCallingUid();
5622        final int callingUserId = UserHandle.getUserId(callingUid);
5623        // Map to base uids.
5624        uid = UserHandle.getAppId(uid);
5625        // reader
5626        synchronized (mPackages) {
5627            final PackageParser.SigningDetails signingDetails;
5628            final Object obj = mSettings.getUserIdLPr(uid);
5629            if (obj != null) {
5630                if (obj instanceof SharedUserSetting) {
5631                    final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5632                    if (isCallerInstantApp) {
5633                        return false;
5634                    }
5635                    signingDetails = ((SharedUserSetting)obj).signatures.mSigningDetails;
5636                } else if (obj instanceof PackageSetting) {
5637                    final PackageSetting ps = (PackageSetting) obj;
5638                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5639                        return false;
5640                    }
5641                    signingDetails = ps.signatures.mSigningDetails;
5642                } else {
5643                    return false;
5644                }
5645            } else {
5646                return false;
5647            }
5648            switch (type) {
5649                case CERT_INPUT_RAW_X509:
5650                    return signingDetails.hasCertificate(certificate);
5651                case CERT_INPUT_SHA256:
5652                    return signingDetails.hasSha256Certificate(certificate);
5653                default:
5654                    return false;
5655            }
5656        }
5657    }
5658
5659    /**
5660     * This method should typically only be used when granting or revoking
5661     * permissions, since the app may immediately restart after this call.
5662     * <p>
5663     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5664     * guard your work against the app being relaunched.
5665     */
5666    private void killUid(int appId, int userId, String reason) {
5667        final long identity = Binder.clearCallingIdentity();
5668        try {
5669            IActivityManager am = ActivityManager.getService();
5670            if (am != null) {
5671                try {
5672                    am.killUid(appId, userId, reason);
5673                } catch (RemoteException e) {
5674                    /* ignore - same process */
5675                }
5676            }
5677        } finally {
5678            Binder.restoreCallingIdentity(identity);
5679        }
5680    }
5681
5682    /**
5683     * If the database version for this type of package (internal storage or
5684     * external storage) is less than the version where package signatures
5685     * were updated, return true.
5686     */
5687    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5688        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5689        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5690    }
5691
5692    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5693        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5694        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5695    }
5696
5697    @Override
5698    public List<String> getAllPackages() {
5699        final int callingUid = Binder.getCallingUid();
5700        final int callingUserId = UserHandle.getUserId(callingUid);
5701        synchronized (mPackages) {
5702            if (canViewInstantApps(callingUid, callingUserId)) {
5703                return new ArrayList<String>(mPackages.keySet());
5704            }
5705            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5706            final List<String> result = new ArrayList<>();
5707            if (instantAppPkgName != null) {
5708                // caller is an instant application; filter unexposed applications
5709                for (PackageParser.Package pkg : mPackages.values()) {
5710                    if (!pkg.visibleToInstantApps) {
5711                        continue;
5712                    }
5713                    result.add(pkg.packageName);
5714                }
5715            } else {
5716                // caller is a normal application; filter instant applications
5717                for (PackageParser.Package pkg : mPackages.values()) {
5718                    final PackageSetting ps =
5719                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5720                    if (ps != null
5721                            && ps.getInstantApp(callingUserId)
5722                            && !mInstantAppRegistry.isInstantAccessGranted(
5723                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5724                        continue;
5725                    }
5726                    result.add(pkg.packageName);
5727                }
5728            }
5729            return result;
5730        }
5731    }
5732
5733    @Override
5734    public String[] getPackagesForUid(int uid) {
5735        final int callingUid = Binder.getCallingUid();
5736        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5737        final int userId = UserHandle.getUserId(uid);
5738        uid = UserHandle.getAppId(uid);
5739        // reader
5740        synchronized (mPackages) {
5741            Object obj = mSettings.getUserIdLPr(uid);
5742            if (obj instanceof SharedUserSetting) {
5743                if (isCallerInstantApp) {
5744                    return null;
5745                }
5746                final SharedUserSetting sus = (SharedUserSetting) obj;
5747                final int N = sus.packages.size();
5748                String[] res = new String[N];
5749                final Iterator<PackageSetting> it = sus.packages.iterator();
5750                int i = 0;
5751                while (it.hasNext()) {
5752                    PackageSetting ps = it.next();
5753                    if (ps.getInstalled(userId)) {
5754                        res[i++] = ps.name;
5755                    } else {
5756                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5757                    }
5758                }
5759                return res;
5760            } else if (obj instanceof PackageSetting) {
5761                final PackageSetting ps = (PackageSetting) obj;
5762                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5763                    return new String[]{ps.name};
5764                }
5765            }
5766        }
5767        return null;
5768    }
5769
5770    @Override
5771    public String getNameForUid(int uid) {
5772        final int callingUid = Binder.getCallingUid();
5773        if (getInstantAppPackageName(callingUid) != null) {
5774            return null;
5775        }
5776        synchronized (mPackages) {
5777            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5778            if (obj instanceof SharedUserSetting) {
5779                final SharedUserSetting sus = (SharedUserSetting) obj;
5780                return sus.name + ":" + sus.userId;
5781            } else if (obj instanceof PackageSetting) {
5782                final PackageSetting ps = (PackageSetting) obj;
5783                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5784                    return null;
5785                }
5786                return ps.name;
5787            }
5788            return null;
5789        }
5790    }
5791
5792    @Override
5793    public String[] getNamesForUids(int[] uids) {
5794        if (uids == null || uids.length == 0) {
5795            return null;
5796        }
5797        final int callingUid = Binder.getCallingUid();
5798        if (getInstantAppPackageName(callingUid) != null) {
5799            return null;
5800        }
5801        final String[] names = new String[uids.length];
5802        synchronized (mPackages) {
5803            for (int i = uids.length - 1; i >= 0; i--) {
5804                final int uid = uids[i];
5805                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5806                if (obj instanceof SharedUserSetting) {
5807                    final SharedUserSetting sus = (SharedUserSetting) obj;
5808                    names[i] = "shared:" + sus.name;
5809                } else if (obj instanceof PackageSetting) {
5810                    final PackageSetting ps = (PackageSetting) obj;
5811                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5812                        names[i] = null;
5813                    } else {
5814                        names[i] = ps.name;
5815                    }
5816                } else {
5817                    names[i] = null;
5818                }
5819            }
5820        }
5821        return names;
5822    }
5823
5824    @Override
5825    public int getUidForSharedUser(String sharedUserName) {
5826        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5827            return -1;
5828        }
5829        if (sharedUserName == null) {
5830            return -1;
5831        }
5832        // reader
5833        synchronized (mPackages) {
5834            SharedUserSetting suid;
5835            try {
5836                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5837                if (suid != null) {
5838                    return suid.userId;
5839                }
5840            } catch (PackageManagerException ignore) {
5841                // can't happen, but, still need to catch it
5842            }
5843            return -1;
5844        }
5845    }
5846
5847    @Override
5848    public int getFlagsForUid(int uid) {
5849        final int callingUid = Binder.getCallingUid();
5850        if (getInstantAppPackageName(callingUid) != null) {
5851            return 0;
5852        }
5853        synchronized (mPackages) {
5854            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5855            if (obj instanceof SharedUserSetting) {
5856                final SharedUserSetting sus = (SharedUserSetting) obj;
5857                return sus.pkgFlags;
5858            } else if (obj instanceof PackageSetting) {
5859                final PackageSetting ps = (PackageSetting) obj;
5860                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5861                    return 0;
5862                }
5863                return ps.pkgFlags;
5864            }
5865        }
5866        return 0;
5867    }
5868
5869    @Override
5870    public int getPrivateFlagsForUid(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.pkgPrivateFlags;
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.pkgPrivateFlags;
5886            }
5887        }
5888        return 0;
5889    }
5890
5891    @Override
5892    public boolean isUidPrivileged(int uid) {
5893        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5894            return false;
5895        }
5896        uid = UserHandle.getAppId(uid);
5897        // reader
5898        synchronized (mPackages) {
5899            Object obj = mSettings.getUserIdLPr(uid);
5900            if (obj instanceof SharedUserSetting) {
5901                final SharedUserSetting sus = (SharedUserSetting) obj;
5902                final Iterator<PackageSetting> it = sus.packages.iterator();
5903                while (it.hasNext()) {
5904                    if (it.next().isPrivileged()) {
5905                        return true;
5906                    }
5907                }
5908            } else if (obj instanceof PackageSetting) {
5909                final PackageSetting ps = (PackageSetting) obj;
5910                return ps.isPrivileged();
5911            }
5912        }
5913        return false;
5914    }
5915
5916    @Override
5917    public String[] getAppOpPermissionPackages(String permName) {
5918        return mPermissionManager.getAppOpPermissionPackages(permName);
5919    }
5920
5921    @Override
5922    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5923            int flags, int userId) {
5924        return resolveIntentInternal(
5925                intent, resolvedType, flags, userId, false /*resolveForStart*/);
5926    }
5927
5928    /**
5929     * Normally instant apps can only be resolved when they're visible to the caller.
5930     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
5931     * since we need to allow the system to start any installed application.
5932     */
5933    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5934            int flags, int userId, boolean resolveForStart) {
5935        try {
5936            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5937
5938            if (!sUserManager.exists(userId)) return null;
5939            final int callingUid = Binder.getCallingUid();
5940            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
5941            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5942                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5943
5944            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5945            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5946                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
5947            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5948
5949            final ResolveInfo bestChoice =
5950                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5951            return bestChoice;
5952        } finally {
5953            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5954        }
5955    }
5956
5957    @Override
5958    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5959        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5960            throw new SecurityException(
5961                    "findPersistentPreferredActivity can only be run by the system");
5962        }
5963        if (!sUserManager.exists(userId)) {
5964            return null;
5965        }
5966        final int callingUid = Binder.getCallingUid();
5967        intent = updateIntentForResolve(intent);
5968        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5969        final int flags = updateFlagsForResolve(
5970                0, userId, intent, callingUid, false /*includeInstantApps*/);
5971        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5972                userId);
5973        synchronized (mPackages) {
5974            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5975                    userId);
5976        }
5977    }
5978
5979    @Override
5980    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5981            IntentFilter filter, int match, ComponentName activity) {
5982        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5983            return;
5984        }
5985        final int userId = UserHandle.getCallingUserId();
5986        if (DEBUG_PREFERRED) {
5987            Log.v(TAG, "setLastChosenActivity intent=" + intent
5988                + " resolvedType=" + resolvedType
5989                + " flags=" + flags
5990                + " filter=" + filter
5991                + " match=" + match
5992                + " activity=" + activity);
5993            filter.dump(new PrintStreamPrinter(System.out), "    ");
5994        }
5995        intent.setComponent(null);
5996        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5997                userId);
5998        // Find any earlier preferred or last chosen entries and nuke them
5999        findPreferredActivity(intent, resolvedType,
6000                flags, query, 0, false, true, false, userId);
6001        // Add the new activity as the last chosen for this filter
6002        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6003                "Setting last chosen");
6004    }
6005
6006    @Override
6007    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6008        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6009            return null;
6010        }
6011        final int userId = UserHandle.getCallingUserId();
6012        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6013        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6014                userId);
6015        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6016                false, false, false, userId);
6017    }
6018
6019    /**
6020     * Returns whether or not instant apps have been disabled remotely.
6021     */
6022    private boolean areWebInstantAppsDisabled() {
6023        return mWebInstantAppsDisabled;
6024    }
6025
6026    private boolean isInstantAppResolutionAllowed(
6027            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6028            boolean skipPackageCheck) {
6029        if (mInstantAppResolverConnection == null) {
6030            return false;
6031        }
6032        if (mInstantAppInstallerActivity == null) {
6033            return false;
6034        }
6035        if (intent.getComponent() != null) {
6036            return false;
6037        }
6038        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6039            return false;
6040        }
6041        if (!skipPackageCheck && intent.getPackage() != null) {
6042            return false;
6043        }
6044        if (!intent.isWebIntent()) {
6045            // for non web intents, we should not resolve externally if an app already exists to
6046            // handle it or if the caller didn't explicitly request it.
6047            if ((resolvedActivities != null && resolvedActivities.size() != 0)
6048                    || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) == 0) {
6049                return false;
6050            }
6051        } else {
6052            if (intent.getData() == null || TextUtils.isEmpty(intent.getData().getHost())) {
6053                return false;
6054            } else if (areWebInstantAppsDisabled()) {
6055                return false;
6056            }
6057        }
6058        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6059        // Or if there's already an ephemeral app installed that handles the action
6060        synchronized (mPackages) {
6061            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6062            for (int n = 0; n < count; n++) {
6063                final ResolveInfo info = resolvedActivities.get(n);
6064                final String packageName = info.activityInfo.packageName;
6065                final PackageSetting ps = mSettings.mPackages.get(packageName);
6066                if (ps != null) {
6067                    // only check domain verification status if the app is not a browser
6068                    if (!info.handleAllWebDataURI) {
6069                        // Try to get the status from User settings first
6070                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6071                        final int status = (int) (packedStatus >> 32);
6072                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6073                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6074                            if (DEBUG_INSTANT) {
6075                                Slog.v(TAG, "DENY instant app;"
6076                                    + " pkg: " + packageName + ", status: " + status);
6077                            }
6078                            return false;
6079                        }
6080                    }
6081                    if (ps.getInstantApp(userId)) {
6082                        if (DEBUG_INSTANT) {
6083                            Slog.v(TAG, "DENY instant app installed;"
6084                                    + " pkg: " + packageName);
6085                        }
6086                        return false;
6087                    }
6088                }
6089            }
6090        }
6091        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6092        return true;
6093    }
6094
6095    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6096            Intent origIntent, String resolvedType, String callingPackage,
6097            Bundle verificationBundle, int userId) {
6098        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6099                new InstantAppRequest(responseObj, origIntent, resolvedType,
6100                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6101        mHandler.sendMessage(msg);
6102    }
6103
6104    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6105            int flags, List<ResolveInfo> query, int userId) {
6106        if (query != null) {
6107            final int N = query.size();
6108            if (N == 1) {
6109                return query.get(0);
6110            } else if (N > 1) {
6111                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6112                // If there is more than one activity with the same priority,
6113                // then let the user decide between them.
6114                ResolveInfo r0 = query.get(0);
6115                ResolveInfo r1 = query.get(1);
6116                if (DEBUG_INTENT_MATCHING || debug) {
6117                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6118                            + r1.activityInfo.name + "=" + r1.priority);
6119                }
6120                // If the first activity has a higher priority, or a different
6121                // default, then it is always desirable to pick it.
6122                if (r0.priority != r1.priority
6123                        || r0.preferredOrder != r1.preferredOrder
6124                        || r0.isDefault != r1.isDefault) {
6125                    return query.get(0);
6126                }
6127                // If we have saved a preference for a preferred activity for
6128                // this Intent, use that.
6129                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6130                        flags, query, r0.priority, true, false, debug, userId);
6131                if (ri != null) {
6132                    return ri;
6133                }
6134                // If we have an ephemeral app, use it
6135                for (int i = 0; i < N; i++) {
6136                    ri = query.get(i);
6137                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6138                        final String packageName = ri.activityInfo.packageName;
6139                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6140                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6141                        final int status = (int)(packedStatus >> 32);
6142                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6143                            return ri;
6144                        }
6145                    }
6146                }
6147                ri = new ResolveInfo(mResolveInfo);
6148                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6149                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6150                // If all of the options come from the same package, show the application's
6151                // label and icon instead of the generic resolver's.
6152                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6153                // and then throw away the ResolveInfo itself, meaning that the caller loses
6154                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6155                // a fallback for this case; we only set the target package's resources on
6156                // the ResolveInfo, not the ActivityInfo.
6157                final String intentPackage = intent.getPackage();
6158                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6159                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6160                    ri.resolvePackageName = intentPackage;
6161                    if (userNeedsBadging(userId)) {
6162                        ri.noResourceId = true;
6163                    } else {
6164                        ri.icon = appi.icon;
6165                    }
6166                    ri.iconResourceId = appi.icon;
6167                    ri.labelRes = appi.labelRes;
6168                }
6169                ri.activityInfo.applicationInfo = new ApplicationInfo(
6170                        ri.activityInfo.applicationInfo);
6171                if (userId != 0) {
6172                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6173                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6174                }
6175                // Make sure that the resolver is displayable in car mode
6176                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6177                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6178                return ri;
6179            }
6180        }
6181        return null;
6182    }
6183
6184    /**
6185     * Return true if the given list is not empty and all of its contents have
6186     * an activityInfo with the given package name.
6187     */
6188    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6189        if (ArrayUtils.isEmpty(list)) {
6190            return false;
6191        }
6192        for (int i = 0, N = list.size(); i < N; i++) {
6193            final ResolveInfo ri = list.get(i);
6194            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6195            if (ai == null || !packageName.equals(ai.packageName)) {
6196                return false;
6197            }
6198        }
6199        return true;
6200    }
6201
6202    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6203            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6204        final int N = query.size();
6205        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6206                .get(userId);
6207        // Get the list of persistent preferred activities that handle the intent
6208        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6209        List<PersistentPreferredActivity> pprefs = ppir != null
6210                ? ppir.queryIntent(intent, resolvedType,
6211                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6212                        userId)
6213                : null;
6214        if (pprefs != null && pprefs.size() > 0) {
6215            final int M = pprefs.size();
6216            for (int i=0; i<M; i++) {
6217                final PersistentPreferredActivity ppa = pprefs.get(i);
6218                if (DEBUG_PREFERRED || debug) {
6219                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6220                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6221                            + "\n  component=" + ppa.mComponent);
6222                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6223                }
6224                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6225                        flags | MATCH_DISABLED_COMPONENTS, userId);
6226                if (DEBUG_PREFERRED || debug) {
6227                    Slog.v(TAG, "Found persistent preferred activity:");
6228                    if (ai != null) {
6229                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6230                    } else {
6231                        Slog.v(TAG, "  null");
6232                    }
6233                }
6234                if (ai == null) {
6235                    // This previously registered persistent preferred activity
6236                    // component is no longer known. Ignore it and do NOT remove it.
6237                    continue;
6238                }
6239                for (int j=0; j<N; j++) {
6240                    final ResolveInfo ri = query.get(j);
6241                    if (!ri.activityInfo.applicationInfo.packageName
6242                            .equals(ai.applicationInfo.packageName)) {
6243                        continue;
6244                    }
6245                    if (!ri.activityInfo.name.equals(ai.name)) {
6246                        continue;
6247                    }
6248                    //  Found a persistent preference that can handle the intent.
6249                    if (DEBUG_PREFERRED || debug) {
6250                        Slog.v(TAG, "Returning persistent preferred activity: " +
6251                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6252                    }
6253                    return ri;
6254                }
6255            }
6256        }
6257        return null;
6258    }
6259
6260    // TODO: handle preferred activities missing while user has amnesia
6261    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6262            List<ResolveInfo> query, int priority, boolean always,
6263            boolean removeMatches, boolean debug, int userId) {
6264        if (!sUserManager.exists(userId)) return null;
6265        final int callingUid = Binder.getCallingUid();
6266        flags = updateFlagsForResolve(
6267                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6268        intent = updateIntentForResolve(intent);
6269        // writer
6270        synchronized (mPackages) {
6271            // Try to find a matching persistent preferred activity.
6272            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6273                    debug, userId);
6274
6275            // If a persistent preferred activity matched, use it.
6276            if (pri != null) {
6277                return pri;
6278            }
6279
6280            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6281            // Get the list of preferred activities that handle the intent
6282            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6283            List<PreferredActivity> prefs = pir != null
6284                    ? pir.queryIntent(intent, resolvedType,
6285                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6286                            userId)
6287                    : null;
6288            if (prefs != null && prefs.size() > 0) {
6289                boolean changed = false;
6290                try {
6291                    // First figure out how good the original match set is.
6292                    // We will only allow preferred activities that came
6293                    // from the same match quality.
6294                    int match = 0;
6295
6296                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6297
6298                    final int N = query.size();
6299                    for (int j=0; j<N; j++) {
6300                        final ResolveInfo ri = query.get(j);
6301                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6302                                + ": 0x" + Integer.toHexString(match));
6303                        if (ri.match > match) {
6304                            match = ri.match;
6305                        }
6306                    }
6307
6308                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6309                            + Integer.toHexString(match));
6310
6311                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6312                    final int M = prefs.size();
6313                    for (int i=0; i<M; i++) {
6314                        final PreferredActivity pa = prefs.get(i);
6315                        if (DEBUG_PREFERRED || debug) {
6316                            Slog.v(TAG, "Checking PreferredActivity ds="
6317                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6318                                    + "\n  component=" + pa.mPref.mComponent);
6319                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6320                        }
6321                        if (pa.mPref.mMatch != match) {
6322                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6323                                    + Integer.toHexString(pa.mPref.mMatch));
6324                            continue;
6325                        }
6326                        // If it's not an "always" type preferred activity and that's what we're
6327                        // looking for, skip it.
6328                        if (always && !pa.mPref.mAlways) {
6329                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6330                            continue;
6331                        }
6332                        final ActivityInfo ai = getActivityInfo(
6333                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6334                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6335                                userId);
6336                        if (DEBUG_PREFERRED || debug) {
6337                            Slog.v(TAG, "Found preferred activity:");
6338                            if (ai != null) {
6339                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6340                            } else {
6341                                Slog.v(TAG, "  null");
6342                            }
6343                        }
6344                        if (ai == null) {
6345                            // This previously registered preferred activity
6346                            // component is no longer known.  Most likely an update
6347                            // to the app was installed and in the new version this
6348                            // component no longer exists.  Clean it up by removing
6349                            // it from the preferred activities list, and skip it.
6350                            Slog.w(TAG, "Removing dangling preferred activity: "
6351                                    + pa.mPref.mComponent);
6352                            pir.removeFilter(pa);
6353                            changed = true;
6354                            continue;
6355                        }
6356                        for (int j=0; j<N; j++) {
6357                            final ResolveInfo ri = query.get(j);
6358                            if (!ri.activityInfo.applicationInfo.packageName
6359                                    .equals(ai.applicationInfo.packageName)) {
6360                                continue;
6361                            }
6362                            if (!ri.activityInfo.name.equals(ai.name)) {
6363                                continue;
6364                            }
6365
6366                            if (removeMatches) {
6367                                pir.removeFilter(pa);
6368                                changed = true;
6369                                if (DEBUG_PREFERRED) {
6370                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6371                                }
6372                                break;
6373                            }
6374
6375                            // Okay we found a previously set preferred or last chosen app.
6376                            // If the result set is different from when this
6377                            // was created, and is not a subset of the preferred set, we need to
6378                            // clear it and re-ask the user their preference, if we're looking for
6379                            // an "always" type entry.
6380                            if (always && !pa.mPref.sameSet(query)) {
6381                                if (pa.mPref.isSuperset(query)) {
6382                                    // some components of the set are no longer present in
6383                                    // the query, but the preferred activity can still be reused
6384                                    if (DEBUG_PREFERRED) {
6385                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6386                                                + " still valid as only non-preferred components"
6387                                                + " were removed for " + intent + " type "
6388                                                + resolvedType);
6389                                    }
6390                                    // remove obsolete components and re-add the up-to-date filter
6391                                    PreferredActivity freshPa = new PreferredActivity(pa,
6392                                            pa.mPref.mMatch,
6393                                            pa.mPref.discardObsoleteComponents(query),
6394                                            pa.mPref.mComponent,
6395                                            pa.mPref.mAlways);
6396                                    pir.removeFilter(pa);
6397                                    pir.addFilter(freshPa);
6398                                    changed = true;
6399                                } else {
6400                                    Slog.i(TAG,
6401                                            "Result set changed, dropping preferred activity for "
6402                                                    + intent + " type " + resolvedType);
6403                                    if (DEBUG_PREFERRED) {
6404                                        Slog.v(TAG, "Removing preferred activity since set changed "
6405                                                + pa.mPref.mComponent);
6406                                    }
6407                                    pir.removeFilter(pa);
6408                                    // Re-add the filter as a "last chosen" entry (!always)
6409                                    PreferredActivity lastChosen = new PreferredActivity(
6410                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6411                                    pir.addFilter(lastChosen);
6412                                    changed = true;
6413                                    return null;
6414                                }
6415                            }
6416
6417                            // Yay! Either the set matched or we're looking for the last chosen
6418                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6419                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6420                            return ri;
6421                        }
6422                    }
6423                } finally {
6424                    if (changed) {
6425                        if (DEBUG_PREFERRED) {
6426                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6427                        }
6428                        scheduleWritePackageRestrictionsLocked(userId);
6429                    }
6430                }
6431            }
6432        }
6433        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6434        return null;
6435    }
6436
6437    /*
6438     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6439     */
6440    @Override
6441    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6442            int targetUserId) {
6443        mContext.enforceCallingOrSelfPermission(
6444                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6445        List<CrossProfileIntentFilter> matches =
6446                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6447        if (matches != null) {
6448            int size = matches.size();
6449            for (int i = 0; i < size; i++) {
6450                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6451            }
6452        }
6453        if (intent.hasWebURI()) {
6454            // cross-profile app linking works only towards the parent.
6455            final int callingUid = Binder.getCallingUid();
6456            final UserInfo parent = getProfileParent(sourceUserId);
6457            synchronized(mPackages) {
6458                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6459                        false /*includeInstantApps*/);
6460                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6461                        intent, resolvedType, flags, sourceUserId, parent.id);
6462                return xpDomainInfo != null;
6463            }
6464        }
6465        return false;
6466    }
6467
6468    private UserInfo getProfileParent(int userId) {
6469        final long identity = Binder.clearCallingIdentity();
6470        try {
6471            return sUserManager.getProfileParent(userId);
6472        } finally {
6473            Binder.restoreCallingIdentity(identity);
6474        }
6475    }
6476
6477    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6478            String resolvedType, int userId) {
6479        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6480        if (resolver != null) {
6481            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6482        }
6483        return null;
6484    }
6485
6486    @Override
6487    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6488            String resolvedType, int flags, int userId) {
6489        try {
6490            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6491
6492            return new ParceledListSlice<>(
6493                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6494        } finally {
6495            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6496        }
6497    }
6498
6499    /**
6500     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6501     * instant, returns {@code null}.
6502     */
6503    private String getInstantAppPackageName(int callingUid) {
6504        synchronized (mPackages) {
6505            // If the caller is an isolated app use the owner's uid for the lookup.
6506            if (Process.isIsolated(callingUid)) {
6507                callingUid = mIsolatedOwners.get(callingUid);
6508            }
6509            final int appId = UserHandle.getAppId(callingUid);
6510            final Object obj = mSettings.getUserIdLPr(appId);
6511            if (obj instanceof PackageSetting) {
6512                final PackageSetting ps = (PackageSetting) obj;
6513                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6514                return isInstantApp ? ps.pkg.packageName : null;
6515            }
6516        }
6517        return null;
6518    }
6519
6520    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6521            String resolvedType, int flags, int userId) {
6522        return queryIntentActivitiesInternal(
6523                intent, resolvedType, flags, Binder.getCallingUid(), userId,
6524                false /*resolveForStart*/, true /*allowDynamicSplits*/);
6525    }
6526
6527    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6528            String resolvedType, int flags, int filterCallingUid, int userId,
6529            boolean resolveForStart, boolean allowDynamicSplits) {
6530        if (!sUserManager.exists(userId)) return Collections.emptyList();
6531        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6532        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6533                false /* requireFullPermission */, false /* checkShell */,
6534                "query intent activities");
6535        final String pkgName = intent.getPackage();
6536        ComponentName comp = intent.getComponent();
6537        if (comp == null) {
6538            if (intent.getSelector() != null) {
6539                intent = intent.getSelector();
6540                comp = intent.getComponent();
6541            }
6542        }
6543
6544        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6545                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6546        if (comp != null) {
6547            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6548            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6549            if (ai != null) {
6550                // When specifying an explicit component, we prevent the activity from being
6551                // used when either 1) the calling package is normal and the activity is within
6552                // an ephemeral application or 2) the calling package is ephemeral and the
6553                // activity is not visible to ephemeral applications.
6554                final boolean matchInstantApp =
6555                        (flags & PackageManager.MATCH_INSTANT) != 0;
6556                final boolean matchVisibleToInstantAppOnly =
6557                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6558                final boolean matchExplicitlyVisibleOnly =
6559                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6560                final boolean isCallerInstantApp =
6561                        instantAppPkgName != null;
6562                final boolean isTargetSameInstantApp =
6563                        comp.getPackageName().equals(instantAppPkgName);
6564                final boolean isTargetInstantApp =
6565                        (ai.applicationInfo.privateFlags
6566                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6567                final boolean isTargetVisibleToInstantApp =
6568                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6569                final boolean isTargetExplicitlyVisibleToInstantApp =
6570                        isTargetVisibleToInstantApp
6571                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6572                final boolean isTargetHiddenFromInstantApp =
6573                        !isTargetVisibleToInstantApp
6574                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6575                final boolean blockResolution =
6576                        !isTargetSameInstantApp
6577                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6578                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6579                                        && isTargetHiddenFromInstantApp));
6580                if (!blockResolution) {
6581                    final ResolveInfo ri = new ResolveInfo();
6582                    ri.activityInfo = ai;
6583                    list.add(ri);
6584                }
6585            }
6586            return applyPostResolutionFilter(
6587                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent);
6588        }
6589
6590        // reader
6591        boolean sortResult = false;
6592        boolean addInstant = false;
6593        List<ResolveInfo> result;
6594        synchronized (mPackages) {
6595            if (pkgName == null) {
6596                List<CrossProfileIntentFilter> matchingFilters =
6597                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6598                // Check for results that need to skip the current profile.
6599                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6600                        resolvedType, flags, userId);
6601                if (xpResolveInfo != null) {
6602                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6603                    xpResult.add(xpResolveInfo);
6604                    return applyPostResolutionFilter(
6605                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6606                            allowDynamicSplits, filterCallingUid, userId, intent);
6607                }
6608
6609                // Check for results in the current profile.
6610                result = filterIfNotSystemUser(mActivities.queryIntent(
6611                        intent, resolvedType, flags, userId), userId);
6612                addInstant = isInstantAppResolutionAllowed(intent, result, userId,
6613                        false /*skipPackageCheck*/);
6614                // Check for cross profile results.
6615                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6616                xpResolveInfo = queryCrossProfileIntents(
6617                        matchingFilters, intent, resolvedType, flags, userId,
6618                        hasNonNegativePriorityResult);
6619                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6620                    boolean isVisibleToUser = filterIfNotSystemUser(
6621                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6622                    if (isVisibleToUser) {
6623                        result.add(xpResolveInfo);
6624                        sortResult = true;
6625                    }
6626                }
6627                if (intent.hasWebURI()) {
6628                    CrossProfileDomainInfo xpDomainInfo = null;
6629                    final UserInfo parent = getProfileParent(userId);
6630                    if (parent != null) {
6631                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6632                                flags, userId, parent.id);
6633                    }
6634                    if (xpDomainInfo != null) {
6635                        if (xpResolveInfo != null) {
6636                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6637                            // in the result.
6638                            result.remove(xpResolveInfo);
6639                        }
6640                        if (result.size() == 0 && !addInstant) {
6641                            // No result in current profile, but found candidate in parent user.
6642                            // And we are not going to add emphemeral app, so we can return the
6643                            // result straight away.
6644                            result.add(xpDomainInfo.resolveInfo);
6645                            return applyPostResolutionFilter(result, instantAppPkgName,
6646                                    allowDynamicSplits, filterCallingUid, userId, intent);
6647                        }
6648                    } else if (result.size() <= 1 && !addInstant) {
6649                        // No result in parent user and <= 1 result in current profile, and we
6650                        // are not going to add emphemeral app, so we can return the result without
6651                        // further processing.
6652                        return applyPostResolutionFilter(result, instantAppPkgName,
6653                                allowDynamicSplits, filterCallingUid, userId, intent);
6654                    }
6655                    // We have more than one candidate (combining results from current and parent
6656                    // profile), so we need filtering and sorting.
6657                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6658                            intent, flags, result, xpDomainInfo, userId);
6659                    sortResult = true;
6660                }
6661            } else {
6662                final PackageParser.Package pkg = mPackages.get(pkgName);
6663                result = null;
6664                if (pkg != null) {
6665                    result = filterIfNotSystemUser(
6666                            mActivities.queryIntentForPackage(
6667                                    intent, resolvedType, flags, pkg.activities, userId),
6668                            userId);
6669                }
6670                if (result == null || result.size() == 0) {
6671                    // the caller wants to resolve for a particular package; however, there
6672                    // were no installed results, so, try to find an ephemeral result
6673                    addInstant = isInstantAppResolutionAllowed(
6674                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6675                    if (result == null) {
6676                        result = new ArrayList<>();
6677                    }
6678                }
6679            }
6680        }
6681        if (addInstant) {
6682            result = maybeAddInstantAppInstaller(
6683                    result, intent, resolvedType, flags, userId, resolveForStart);
6684        }
6685        if (sortResult) {
6686            Collections.sort(result, mResolvePrioritySorter);
6687        }
6688        return applyPostResolutionFilter(
6689                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent);
6690    }
6691
6692    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6693            String resolvedType, int flags, int userId, boolean resolveForStart) {
6694        // first, check to see if we've got an instant app already installed
6695        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6696        ResolveInfo localInstantApp = null;
6697        boolean blockResolution = false;
6698        if (!alreadyResolvedLocally) {
6699            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6700                    flags
6701                        | PackageManager.GET_RESOLVED_FILTER
6702                        | PackageManager.MATCH_INSTANT
6703                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6704                    userId);
6705            for (int i = instantApps.size() - 1; i >= 0; --i) {
6706                final ResolveInfo info = instantApps.get(i);
6707                final String packageName = info.activityInfo.packageName;
6708                final PackageSetting ps = mSettings.mPackages.get(packageName);
6709                if (ps.getInstantApp(userId)) {
6710                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6711                    final int status = (int)(packedStatus >> 32);
6712                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6713                        // there's a local instant application installed, but, the user has
6714                        // chosen to never use it; skip resolution and don't acknowledge
6715                        // an instant application is even available
6716                        if (DEBUG_INSTANT) {
6717                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6718                        }
6719                        blockResolution = true;
6720                        break;
6721                    } else {
6722                        // we have a locally installed instant application; skip resolution
6723                        // but acknowledge there's an instant application available
6724                        if (DEBUG_INSTANT) {
6725                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6726                        }
6727                        localInstantApp = info;
6728                        break;
6729                    }
6730                }
6731            }
6732        }
6733        // no app installed, let's see if one's available
6734        AuxiliaryResolveInfo auxiliaryResponse = null;
6735        if (!blockResolution) {
6736            if (localInstantApp == null) {
6737                // we don't have an instant app locally, resolve externally
6738                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6739                final InstantAppRequest requestObject = new InstantAppRequest(
6740                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6741                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6742                        resolveForStart);
6743                auxiliaryResponse = InstantAppResolver.doInstantAppResolutionPhaseOne(
6744                        mInstantAppResolverConnection, requestObject);
6745                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6746            } else {
6747                // we have an instant application locally, but, we can't admit that since
6748                // callers shouldn't be able to determine prior browsing. create a dummy
6749                // auxiliary response so the downstream code behaves as if there's an
6750                // instant application available externally. when it comes time to start
6751                // the instant application, we'll do the right thing.
6752                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6753                auxiliaryResponse = new AuxiliaryResolveInfo(null /* failureActivity */,
6754                                        ai.packageName, ai.versionCode, null /* splitName */);
6755            }
6756        }
6757        if (intent.isWebIntent() && auxiliaryResponse == null) {
6758            return result;
6759        }
6760        final PackageSetting ps = mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6761        if (ps == null
6762                || ps.getUserState().get(userId) == null
6763                || !ps.getUserState().get(userId).isEnabled(mInstantAppInstallerActivity, 0)) {
6764            return result;
6765        }
6766        final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6767        ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6768                mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6769        ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6770                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6771        // add a non-generic filter
6772        ephemeralInstaller.filter = new IntentFilter();
6773        if (intent.getAction() != null) {
6774            ephemeralInstaller.filter.addAction(intent.getAction());
6775        }
6776        if (intent.getData() != null && intent.getData().getPath() != null) {
6777            ephemeralInstaller.filter.addDataPath(
6778                    intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6779        }
6780        ephemeralInstaller.isInstantAppAvailable = true;
6781        // make sure this resolver is the default
6782        ephemeralInstaller.isDefault = true;
6783        ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6784        if (DEBUG_INSTANT) {
6785            Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6786        }
6787
6788        result.add(ephemeralInstaller);
6789        return result;
6790    }
6791
6792    private static class CrossProfileDomainInfo {
6793        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6794        ResolveInfo resolveInfo;
6795        /* Best domain verification status of the activities found in the other profile */
6796        int bestDomainVerificationStatus;
6797    }
6798
6799    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6800            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6801        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6802                sourceUserId)) {
6803            return null;
6804        }
6805        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6806                resolvedType, flags, parentUserId);
6807
6808        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6809            return null;
6810        }
6811        CrossProfileDomainInfo result = null;
6812        int size = resultTargetUser.size();
6813        for (int i = 0; i < size; i++) {
6814            ResolveInfo riTargetUser = resultTargetUser.get(i);
6815            // Intent filter verification is only for filters that specify a host. So don't return
6816            // those that handle all web uris.
6817            if (riTargetUser.handleAllWebDataURI) {
6818                continue;
6819            }
6820            String packageName = riTargetUser.activityInfo.packageName;
6821            PackageSetting ps = mSettings.mPackages.get(packageName);
6822            if (ps == null) {
6823                continue;
6824            }
6825            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6826            int status = (int)(verificationState >> 32);
6827            if (result == null) {
6828                result = new CrossProfileDomainInfo();
6829                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6830                        sourceUserId, parentUserId);
6831                result.bestDomainVerificationStatus = status;
6832            } else {
6833                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6834                        result.bestDomainVerificationStatus);
6835            }
6836        }
6837        // Don't consider matches with status NEVER across profiles.
6838        if (result != null && result.bestDomainVerificationStatus
6839                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6840            return null;
6841        }
6842        return result;
6843    }
6844
6845    /**
6846     * Verification statuses are ordered from the worse to the best, except for
6847     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6848     */
6849    private int bestDomainVerificationStatus(int status1, int status2) {
6850        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6851            return status2;
6852        }
6853        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6854            return status1;
6855        }
6856        return (int) MathUtils.max(status1, status2);
6857    }
6858
6859    private boolean isUserEnabled(int userId) {
6860        long callingId = Binder.clearCallingIdentity();
6861        try {
6862            UserInfo userInfo = sUserManager.getUserInfo(userId);
6863            return userInfo != null && userInfo.isEnabled();
6864        } finally {
6865            Binder.restoreCallingIdentity(callingId);
6866        }
6867    }
6868
6869    /**
6870     * Filter out activities with systemUserOnly flag set, when current user is not System.
6871     *
6872     * @return filtered list
6873     */
6874    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6875        if (userId == UserHandle.USER_SYSTEM) {
6876            return resolveInfos;
6877        }
6878        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6879            ResolveInfo info = resolveInfos.get(i);
6880            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6881                resolveInfos.remove(i);
6882            }
6883        }
6884        return resolveInfos;
6885    }
6886
6887    /**
6888     * Filters out ephemeral activities.
6889     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6890     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6891     *
6892     * @param resolveInfos The pre-filtered list of resolved activities
6893     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6894     *          is performed.
6895     * @param intent
6896     * @return A filtered list of resolved activities.
6897     */
6898    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6899            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId,
6900            Intent intent) {
6901        final boolean blockInstant = intent.isWebIntent() && areWebInstantAppsDisabled();
6902        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6903            final ResolveInfo info = resolveInfos.get(i);
6904            // remove locally resolved instant app web results when disabled
6905            if (info.isInstantAppAvailable && blockInstant) {
6906                resolveInfos.remove(i);
6907                continue;
6908            }
6909            // allow activities that are defined in the provided package
6910            if (allowDynamicSplits
6911                    && info.activityInfo != null
6912                    && info.activityInfo.splitName != null
6913                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6914                            info.activityInfo.splitName)) {
6915                if (mInstantAppInstallerActivity == null) {
6916                    if (DEBUG_INSTALL) {
6917                        Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
6918                    }
6919                    resolveInfos.remove(i);
6920                    continue;
6921                }
6922                if (blockInstant && isInstantApp(info.activityInfo.packageName, userId)) {
6923                    resolveInfos.remove(i);
6924                    continue;
6925                }
6926                // requested activity is defined in a split that hasn't been installed yet.
6927                // add the installer to the resolve list
6928                if (DEBUG_INSTALL) {
6929                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6930                }
6931                final ResolveInfo installerInfo = new ResolveInfo(
6932                        mInstantAppInstallerInfo);
6933                final ComponentName installFailureActivity = findInstallFailureActivity(
6934                        info.activityInfo.packageName,  filterCallingUid, userId);
6935                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6936                        installFailureActivity,
6937                        info.activityInfo.packageName,
6938                        info.activityInfo.applicationInfo.versionCode,
6939                        info.activityInfo.splitName);
6940                // add a non-generic filter
6941                installerInfo.filter = new IntentFilter();
6942
6943                // This resolve info may appear in the chooser UI, so let us make it
6944                // look as the one it replaces as far as the user is concerned which
6945                // requires loading the correct label and icon for the resolve info.
6946                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6947                installerInfo.labelRes = info.resolveLabelResId();
6948                installerInfo.icon = info.resolveIconResId();
6949                installerInfo.isInstantAppAvailable = true;
6950                resolveInfos.set(i, installerInfo);
6951                continue;
6952            }
6953            // caller is a full app, don't need to apply any other filtering
6954            if (ephemeralPkgName == null) {
6955                continue;
6956            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
6957                // caller is same app; don't need to apply any other filtering
6958                continue;
6959            }
6960            // allow activities that have been explicitly exposed to ephemeral apps
6961            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6962            if (!isEphemeralApp
6963                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6964                continue;
6965            }
6966            resolveInfos.remove(i);
6967        }
6968        return resolveInfos;
6969    }
6970
6971    /**
6972     * Returns the activity component that can handle install failures.
6973     * <p>By default, the instant application installer handles failures. However, an
6974     * application may want to handle failures on its own. Applications do this by
6975     * creating an activity with an intent filter that handles the action
6976     * {@link Intent#ACTION_INSTALL_FAILURE}.
6977     */
6978    private @Nullable ComponentName findInstallFailureActivity(
6979            String packageName, int filterCallingUid, int userId) {
6980        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
6981        failureActivityIntent.setPackage(packageName);
6982        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
6983        final List<ResolveInfo> result = queryIntentActivitiesInternal(
6984                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
6985                false /*resolveForStart*/, false /*allowDynamicSplits*/);
6986        final int NR = result.size();
6987        if (NR > 0) {
6988            for (int i = 0; i < NR; i++) {
6989                final ResolveInfo info = result.get(i);
6990                if (info.activityInfo.splitName != null) {
6991                    continue;
6992                }
6993                return new ComponentName(packageName, info.activityInfo.name);
6994            }
6995        }
6996        return null;
6997    }
6998
6999    /**
7000     * @param resolveInfos list of resolve infos in descending priority order
7001     * @return if the list contains a resolve info with non-negative priority
7002     */
7003    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7004        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7005    }
7006
7007    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7008            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7009            int userId) {
7010        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7011
7012        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7013            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7014                    candidates.size());
7015        }
7016
7017        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7018        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7019        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7020        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7021        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7022        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7023
7024        synchronized (mPackages) {
7025            final int count = candidates.size();
7026            // First, try to use linked apps. Partition the candidates into four lists:
7027            // one for the final results, one for the "do not use ever", one for "undefined status"
7028            // and finally one for "browser app type".
7029            for (int n=0; n<count; n++) {
7030                ResolveInfo info = candidates.get(n);
7031                String packageName = info.activityInfo.packageName;
7032                PackageSetting ps = mSettings.mPackages.get(packageName);
7033                if (ps != null) {
7034                    // Add to the special match all list (Browser use case)
7035                    if (info.handleAllWebDataURI) {
7036                        matchAllList.add(info);
7037                        continue;
7038                    }
7039                    // Try to get the status from User settings first
7040                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7041                    int status = (int)(packedStatus >> 32);
7042                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7043                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7044                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7045                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7046                                    + " : linkgen=" + linkGeneration);
7047                        }
7048                        // Use link-enabled generation as preferredOrder, i.e.
7049                        // prefer newly-enabled over earlier-enabled.
7050                        info.preferredOrder = linkGeneration;
7051                        alwaysList.add(info);
7052                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7053                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7054                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7055                        }
7056                        neverList.add(info);
7057                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7058                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7059                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7060                        }
7061                        alwaysAskList.add(info);
7062                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7063                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7064                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7065                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7066                        }
7067                        undefinedList.add(info);
7068                    }
7069                }
7070            }
7071
7072            // We'll want to include browser possibilities in a few cases
7073            boolean includeBrowser = false;
7074
7075            // First try to add the "always" resolution(s) for the current user, if any
7076            if (alwaysList.size() > 0) {
7077                result.addAll(alwaysList);
7078            } else {
7079                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7080                result.addAll(undefinedList);
7081                // Maybe add one for the other profile.
7082                if (xpDomainInfo != null && (
7083                        xpDomainInfo.bestDomainVerificationStatus
7084                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7085                    result.add(xpDomainInfo.resolveInfo);
7086                }
7087                includeBrowser = true;
7088            }
7089
7090            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7091            // If there were 'always' entries their preferred order has been set, so we also
7092            // back that off to make the alternatives equivalent
7093            if (alwaysAskList.size() > 0) {
7094                for (ResolveInfo i : result) {
7095                    i.preferredOrder = 0;
7096                }
7097                result.addAll(alwaysAskList);
7098                includeBrowser = true;
7099            }
7100
7101            if (includeBrowser) {
7102                // Also add browsers (all of them or only the default one)
7103                if (DEBUG_DOMAIN_VERIFICATION) {
7104                    Slog.v(TAG, "   ...including browsers in candidate set");
7105                }
7106                if ((matchFlags & MATCH_ALL) != 0) {
7107                    result.addAll(matchAllList);
7108                } else {
7109                    // Browser/generic handling case.  If there's a default browser, go straight
7110                    // to that (but only if there is no other higher-priority match).
7111                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7112                    int maxMatchPrio = 0;
7113                    ResolveInfo defaultBrowserMatch = null;
7114                    final int numCandidates = matchAllList.size();
7115                    for (int n = 0; n < numCandidates; n++) {
7116                        ResolveInfo info = matchAllList.get(n);
7117                        // track the highest overall match priority...
7118                        if (info.priority > maxMatchPrio) {
7119                            maxMatchPrio = info.priority;
7120                        }
7121                        // ...and the highest-priority default browser match
7122                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7123                            if (defaultBrowserMatch == null
7124                                    || (defaultBrowserMatch.priority < info.priority)) {
7125                                if (debug) {
7126                                    Slog.v(TAG, "Considering default browser match " + info);
7127                                }
7128                                defaultBrowserMatch = info;
7129                            }
7130                        }
7131                    }
7132                    if (defaultBrowserMatch != null
7133                            && defaultBrowserMatch.priority >= maxMatchPrio
7134                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7135                    {
7136                        if (debug) {
7137                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7138                        }
7139                        result.add(defaultBrowserMatch);
7140                    } else {
7141                        result.addAll(matchAllList);
7142                    }
7143                }
7144
7145                // If there is nothing selected, add all candidates and remove the ones that the user
7146                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7147                if (result.size() == 0) {
7148                    result.addAll(candidates);
7149                    result.removeAll(neverList);
7150                }
7151            }
7152        }
7153        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7154            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7155                    result.size());
7156            for (ResolveInfo info : result) {
7157                Slog.v(TAG, "  + " + info.activityInfo);
7158            }
7159        }
7160        return result;
7161    }
7162
7163    // Returns a packed value as a long:
7164    //
7165    // high 'int'-sized word: link status: undefined/ask/never/always.
7166    // low 'int'-sized word: relative priority among 'always' results.
7167    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7168        long result = ps.getDomainVerificationStatusForUser(userId);
7169        // if none available, get the master status
7170        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7171            if (ps.getIntentFilterVerificationInfo() != null) {
7172                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7173            }
7174        }
7175        return result;
7176    }
7177
7178    private ResolveInfo querySkipCurrentProfileIntents(
7179            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7180            int flags, int sourceUserId) {
7181        if (matchingFilters != null) {
7182            int size = matchingFilters.size();
7183            for (int i = 0; i < size; i ++) {
7184                CrossProfileIntentFilter filter = matchingFilters.get(i);
7185                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7186                    // Checking if there are activities in the target user that can handle the
7187                    // intent.
7188                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7189                            resolvedType, flags, sourceUserId);
7190                    if (resolveInfo != null) {
7191                        return resolveInfo;
7192                    }
7193                }
7194            }
7195        }
7196        return null;
7197    }
7198
7199    // Return matching ResolveInfo in target user if any.
7200    private ResolveInfo queryCrossProfileIntents(
7201            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7202            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7203        if (matchingFilters != null) {
7204            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7205            // match the same intent. For performance reasons, it is better not to
7206            // run queryIntent twice for the same userId
7207            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7208            int size = matchingFilters.size();
7209            for (int i = 0; i < size; i++) {
7210                CrossProfileIntentFilter filter = matchingFilters.get(i);
7211                int targetUserId = filter.getTargetUserId();
7212                boolean skipCurrentProfile =
7213                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7214                boolean skipCurrentProfileIfNoMatchFound =
7215                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7216                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7217                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7218                    // Checking if there are activities in the target user that can handle the
7219                    // intent.
7220                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7221                            resolvedType, flags, sourceUserId);
7222                    if (resolveInfo != null) return resolveInfo;
7223                    alreadyTriedUserIds.put(targetUserId, true);
7224                }
7225            }
7226        }
7227        return null;
7228    }
7229
7230    /**
7231     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7232     * will forward the intent to the filter's target user.
7233     * Otherwise, returns null.
7234     */
7235    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7236            String resolvedType, int flags, int sourceUserId) {
7237        int targetUserId = filter.getTargetUserId();
7238        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7239                resolvedType, flags, targetUserId);
7240        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7241            // If all the matches in the target profile are suspended, return null.
7242            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7243                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7244                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7245                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7246                            targetUserId);
7247                }
7248            }
7249        }
7250        return null;
7251    }
7252
7253    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7254            int sourceUserId, int targetUserId) {
7255        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7256        long ident = Binder.clearCallingIdentity();
7257        boolean targetIsProfile;
7258        try {
7259            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7260        } finally {
7261            Binder.restoreCallingIdentity(ident);
7262        }
7263        String className;
7264        if (targetIsProfile) {
7265            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7266        } else {
7267            className = FORWARD_INTENT_TO_PARENT;
7268        }
7269        ComponentName forwardingActivityComponentName = new ComponentName(
7270                mAndroidApplication.packageName, className);
7271        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7272                sourceUserId);
7273        if (!targetIsProfile) {
7274            forwardingActivityInfo.showUserIcon = targetUserId;
7275            forwardingResolveInfo.noResourceId = true;
7276        }
7277        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7278        forwardingResolveInfo.priority = 0;
7279        forwardingResolveInfo.preferredOrder = 0;
7280        forwardingResolveInfo.match = 0;
7281        forwardingResolveInfo.isDefault = true;
7282        forwardingResolveInfo.filter = filter;
7283        forwardingResolveInfo.targetUserId = targetUserId;
7284        return forwardingResolveInfo;
7285    }
7286
7287    @Override
7288    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7289            Intent[] specifics, String[] specificTypes, Intent intent,
7290            String resolvedType, int flags, int userId) {
7291        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7292                specificTypes, intent, resolvedType, flags, userId));
7293    }
7294
7295    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7296            Intent[] specifics, String[] specificTypes, Intent intent,
7297            String resolvedType, int flags, int userId) {
7298        if (!sUserManager.exists(userId)) return Collections.emptyList();
7299        final int callingUid = Binder.getCallingUid();
7300        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7301                false /*includeInstantApps*/);
7302        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7303                false /*requireFullPermission*/, false /*checkShell*/,
7304                "query intent activity options");
7305        final String resultsAction = intent.getAction();
7306
7307        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7308                | PackageManager.GET_RESOLVED_FILTER, userId);
7309
7310        if (DEBUG_INTENT_MATCHING) {
7311            Log.v(TAG, "Query " + intent + ": " + results);
7312        }
7313
7314        int specificsPos = 0;
7315        int N;
7316
7317        // todo: note that the algorithm used here is O(N^2).  This
7318        // isn't a problem in our current environment, but if we start running
7319        // into situations where we have more than 5 or 10 matches then this
7320        // should probably be changed to something smarter...
7321
7322        // First we go through and resolve each of the specific items
7323        // that were supplied, taking care of removing any corresponding
7324        // duplicate items in the generic resolve list.
7325        if (specifics != null) {
7326            for (int i=0; i<specifics.length; i++) {
7327                final Intent sintent = specifics[i];
7328                if (sintent == null) {
7329                    continue;
7330                }
7331
7332                if (DEBUG_INTENT_MATCHING) {
7333                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7334                }
7335
7336                String action = sintent.getAction();
7337                if (resultsAction != null && resultsAction.equals(action)) {
7338                    // If this action was explicitly requested, then don't
7339                    // remove things that have it.
7340                    action = null;
7341                }
7342
7343                ResolveInfo ri = null;
7344                ActivityInfo ai = null;
7345
7346                ComponentName comp = sintent.getComponent();
7347                if (comp == null) {
7348                    ri = resolveIntent(
7349                        sintent,
7350                        specificTypes != null ? specificTypes[i] : null,
7351                            flags, userId);
7352                    if (ri == null) {
7353                        continue;
7354                    }
7355                    if (ri == mResolveInfo) {
7356                        // ACK!  Must do something better with this.
7357                    }
7358                    ai = ri.activityInfo;
7359                    comp = new ComponentName(ai.applicationInfo.packageName,
7360                            ai.name);
7361                } else {
7362                    ai = getActivityInfo(comp, flags, userId);
7363                    if (ai == null) {
7364                        continue;
7365                    }
7366                }
7367
7368                // Look for any generic query activities that are duplicates
7369                // of this specific one, and remove them from the results.
7370                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7371                N = results.size();
7372                int j;
7373                for (j=specificsPos; j<N; j++) {
7374                    ResolveInfo sri = results.get(j);
7375                    if ((sri.activityInfo.name.equals(comp.getClassName())
7376                            && sri.activityInfo.applicationInfo.packageName.equals(
7377                                    comp.getPackageName()))
7378                        || (action != null && sri.filter.matchAction(action))) {
7379                        results.remove(j);
7380                        if (DEBUG_INTENT_MATCHING) Log.v(
7381                            TAG, "Removing duplicate item from " + j
7382                            + " due to specific " + specificsPos);
7383                        if (ri == null) {
7384                            ri = sri;
7385                        }
7386                        j--;
7387                        N--;
7388                    }
7389                }
7390
7391                // Add this specific item to its proper place.
7392                if (ri == null) {
7393                    ri = new ResolveInfo();
7394                    ri.activityInfo = ai;
7395                }
7396                results.add(specificsPos, ri);
7397                ri.specificIndex = i;
7398                specificsPos++;
7399            }
7400        }
7401
7402        // Now we go through the remaining generic results and remove any
7403        // duplicate actions that are found here.
7404        N = results.size();
7405        for (int i=specificsPos; i<N-1; i++) {
7406            final ResolveInfo rii = results.get(i);
7407            if (rii.filter == null) {
7408                continue;
7409            }
7410
7411            // Iterate over all of the actions of this result's intent
7412            // filter...  typically this should be just one.
7413            final Iterator<String> it = rii.filter.actionsIterator();
7414            if (it == null) {
7415                continue;
7416            }
7417            while (it.hasNext()) {
7418                final String action = it.next();
7419                if (resultsAction != null && resultsAction.equals(action)) {
7420                    // If this action was explicitly requested, then don't
7421                    // remove things that have it.
7422                    continue;
7423                }
7424                for (int j=i+1; j<N; j++) {
7425                    final ResolveInfo rij = results.get(j);
7426                    if (rij.filter != null && rij.filter.hasAction(action)) {
7427                        results.remove(j);
7428                        if (DEBUG_INTENT_MATCHING) Log.v(
7429                            TAG, "Removing duplicate item from " + j
7430                            + " due to action " + action + " at " + i);
7431                        j--;
7432                        N--;
7433                    }
7434                }
7435            }
7436
7437            // If the caller didn't request filter information, drop it now
7438            // so we don't have to marshall/unmarshall it.
7439            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7440                rii.filter = null;
7441            }
7442        }
7443
7444        // Filter out the caller activity if so requested.
7445        if (caller != null) {
7446            N = results.size();
7447            for (int i=0; i<N; i++) {
7448                ActivityInfo ainfo = results.get(i).activityInfo;
7449                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7450                        && caller.getClassName().equals(ainfo.name)) {
7451                    results.remove(i);
7452                    break;
7453                }
7454            }
7455        }
7456
7457        // If the caller didn't request filter information,
7458        // drop them now so we don't have to
7459        // marshall/unmarshall it.
7460        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7461            N = results.size();
7462            for (int i=0; i<N; i++) {
7463                results.get(i).filter = null;
7464            }
7465        }
7466
7467        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7468        return results;
7469    }
7470
7471    @Override
7472    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7473            String resolvedType, int flags, int userId) {
7474        return new ParceledListSlice<>(
7475                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7476                        false /*allowDynamicSplits*/));
7477    }
7478
7479    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7480            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7481        if (!sUserManager.exists(userId)) return Collections.emptyList();
7482        final int callingUid = Binder.getCallingUid();
7483        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7484                false /*requireFullPermission*/, false /*checkShell*/,
7485                "query intent receivers");
7486        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7487        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7488                false /*includeInstantApps*/);
7489        ComponentName comp = intent.getComponent();
7490        if (comp == null) {
7491            if (intent.getSelector() != null) {
7492                intent = intent.getSelector();
7493                comp = intent.getComponent();
7494            }
7495        }
7496        if (comp != null) {
7497            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7498            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7499            if (ai != null) {
7500                // When specifying an explicit component, we prevent the activity from being
7501                // used when either 1) the calling package is normal and the activity is within
7502                // an instant application or 2) the calling package is ephemeral and the
7503                // activity is not visible to instant applications.
7504                final boolean matchInstantApp =
7505                        (flags & PackageManager.MATCH_INSTANT) != 0;
7506                final boolean matchVisibleToInstantAppOnly =
7507                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7508                final boolean matchExplicitlyVisibleOnly =
7509                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7510                final boolean isCallerInstantApp =
7511                        instantAppPkgName != null;
7512                final boolean isTargetSameInstantApp =
7513                        comp.getPackageName().equals(instantAppPkgName);
7514                final boolean isTargetInstantApp =
7515                        (ai.applicationInfo.privateFlags
7516                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7517                final boolean isTargetVisibleToInstantApp =
7518                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7519                final boolean isTargetExplicitlyVisibleToInstantApp =
7520                        isTargetVisibleToInstantApp
7521                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7522                final boolean isTargetHiddenFromInstantApp =
7523                        !isTargetVisibleToInstantApp
7524                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7525                final boolean blockResolution =
7526                        !isTargetSameInstantApp
7527                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7528                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7529                                        && isTargetHiddenFromInstantApp));
7530                if (!blockResolution) {
7531                    ResolveInfo ri = new ResolveInfo();
7532                    ri.activityInfo = ai;
7533                    list.add(ri);
7534                }
7535            }
7536            return applyPostResolutionFilter(
7537                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7538        }
7539
7540        // reader
7541        synchronized (mPackages) {
7542            String pkgName = intent.getPackage();
7543            if (pkgName == null) {
7544                final List<ResolveInfo> result =
7545                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7546                return applyPostResolutionFilter(
7547                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7548            }
7549            final PackageParser.Package pkg = mPackages.get(pkgName);
7550            if (pkg != null) {
7551                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7552                        intent, resolvedType, flags, pkg.receivers, userId);
7553                return applyPostResolutionFilter(
7554                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7555            }
7556            return Collections.emptyList();
7557        }
7558    }
7559
7560    @Override
7561    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7562        final int callingUid = Binder.getCallingUid();
7563        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7564    }
7565
7566    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7567            int userId, int callingUid) {
7568        if (!sUserManager.exists(userId)) return null;
7569        flags = updateFlagsForResolve(
7570                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7571        List<ResolveInfo> query = queryIntentServicesInternal(
7572                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7573        if (query != null) {
7574            if (query.size() >= 1) {
7575                // If there is more than one service with the same priority,
7576                // just arbitrarily pick the first one.
7577                return query.get(0);
7578            }
7579        }
7580        return null;
7581    }
7582
7583    @Override
7584    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7585            String resolvedType, int flags, int userId) {
7586        final int callingUid = Binder.getCallingUid();
7587        return new ParceledListSlice<>(queryIntentServicesInternal(
7588                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7589    }
7590
7591    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7592            String resolvedType, int flags, int userId, int callingUid,
7593            boolean includeInstantApps) {
7594        if (!sUserManager.exists(userId)) return Collections.emptyList();
7595        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7596                false /*requireFullPermission*/, false /*checkShell*/,
7597                "query intent receivers");
7598        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7599        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7600        ComponentName comp = intent.getComponent();
7601        if (comp == null) {
7602            if (intent.getSelector() != null) {
7603                intent = intent.getSelector();
7604                comp = intent.getComponent();
7605            }
7606        }
7607        if (comp != null) {
7608            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7609            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7610            if (si != null) {
7611                // When specifying an explicit component, we prevent the service from being
7612                // used when either 1) the service is in an instant application and the
7613                // caller is not the same instant application or 2) the calling package is
7614                // ephemeral and the activity is not visible to ephemeral applications.
7615                final boolean matchInstantApp =
7616                        (flags & PackageManager.MATCH_INSTANT) != 0;
7617                final boolean matchVisibleToInstantAppOnly =
7618                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7619                final boolean isCallerInstantApp =
7620                        instantAppPkgName != null;
7621                final boolean isTargetSameInstantApp =
7622                        comp.getPackageName().equals(instantAppPkgName);
7623                final boolean isTargetInstantApp =
7624                        (si.applicationInfo.privateFlags
7625                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7626                final boolean isTargetHiddenFromInstantApp =
7627                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7628                final boolean blockResolution =
7629                        !isTargetSameInstantApp
7630                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7631                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7632                                        && isTargetHiddenFromInstantApp));
7633                if (!blockResolution) {
7634                    final ResolveInfo ri = new ResolveInfo();
7635                    ri.serviceInfo = si;
7636                    list.add(ri);
7637                }
7638            }
7639            return list;
7640        }
7641
7642        // reader
7643        synchronized (mPackages) {
7644            String pkgName = intent.getPackage();
7645            if (pkgName == null) {
7646                return applyPostServiceResolutionFilter(
7647                        mServices.queryIntent(intent, resolvedType, flags, userId),
7648                        instantAppPkgName);
7649            }
7650            final PackageParser.Package pkg = mPackages.get(pkgName);
7651            if (pkg != null) {
7652                return applyPostServiceResolutionFilter(
7653                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7654                                userId),
7655                        instantAppPkgName);
7656            }
7657            return Collections.emptyList();
7658        }
7659    }
7660
7661    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7662            String instantAppPkgName) {
7663        if (instantAppPkgName == null) {
7664            return resolveInfos;
7665        }
7666        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7667            final ResolveInfo info = resolveInfos.get(i);
7668            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7669            // allow services that are defined in the provided package
7670            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7671                if (info.serviceInfo.splitName != null
7672                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7673                                info.serviceInfo.splitName)) {
7674                    // requested service is defined in a split that hasn't been installed yet.
7675                    // add the installer to the resolve list
7676                    if (DEBUG_INSTANT) {
7677                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7678                    }
7679                    final ResolveInfo installerInfo = new ResolveInfo(
7680                            mInstantAppInstallerInfo);
7681                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7682                            null /* installFailureActivity */,
7683                            info.serviceInfo.packageName,
7684                            info.serviceInfo.applicationInfo.versionCode,
7685                            info.serviceInfo.splitName);
7686                    // add a non-generic filter
7687                    installerInfo.filter = new IntentFilter();
7688                    // load resources from the correct package
7689                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7690                    resolveInfos.set(i, installerInfo);
7691                }
7692                continue;
7693            }
7694            // allow services that have been explicitly exposed to ephemeral apps
7695            if (!isEphemeralApp
7696                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7697                continue;
7698            }
7699            resolveInfos.remove(i);
7700        }
7701        return resolveInfos;
7702    }
7703
7704    @Override
7705    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7706            String resolvedType, int flags, int userId) {
7707        return new ParceledListSlice<>(
7708                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7709    }
7710
7711    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7712            Intent intent, String resolvedType, int flags, int userId) {
7713        if (!sUserManager.exists(userId)) return Collections.emptyList();
7714        final int callingUid = Binder.getCallingUid();
7715        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7716        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7717                false /*includeInstantApps*/);
7718        ComponentName comp = intent.getComponent();
7719        if (comp == null) {
7720            if (intent.getSelector() != null) {
7721                intent = intent.getSelector();
7722                comp = intent.getComponent();
7723            }
7724        }
7725        if (comp != null) {
7726            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7727            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7728            if (pi != null) {
7729                // When specifying an explicit component, we prevent the provider from being
7730                // used when either 1) the provider is in an instant application and the
7731                // caller is not the same instant application or 2) the calling package is an
7732                // instant application and the provider is not visible to instant applications.
7733                final boolean matchInstantApp =
7734                        (flags & PackageManager.MATCH_INSTANT) != 0;
7735                final boolean matchVisibleToInstantAppOnly =
7736                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7737                final boolean isCallerInstantApp =
7738                        instantAppPkgName != null;
7739                final boolean isTargetSameInstantApp =
7740                        comp.getPackageName().equals(instantAppPkgName);
7741                final boolean isTargetInstantApp =
7742                        (pi.applicationInfo.privateFlags
7743                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7744                final boolean isTargetHiddenFromInstantApp =
7745                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7746                final boolean blockResolution =
7747                        !isTargetSameInstantApp
7748                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7749                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7750                                        && isTargetHiddenFromInstantApp));
7751                if (!blockResolution) {
7752                    final ResolveInfo ri = new ResolveInfo();
7753                    ri.providerInfo = pi;
7754                    list.add(ri);
7755                }
7756            }
7757            return list;
7758        }
7759
7760        // reader
7761        synchronized (mPackages) {
7762            String pkgName = intent.getPackage();
7763            if (pkgName == null) {
7764                return applyPostContentProviderResolutionFilter(
7765                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7766                        instantAppPkgName);
7767            }
7768            final PackageParser.Package pkg = mPackages.get(pkgName);
7769            if (pkg != null) {
7770                return applyPostContentProviderResolutionFilter(
7771                        mProviders.queryIntentForPackage(
7772                        intent, resolvedType, flags, pkg.providers, userId),
7773                        instantAppPkgName);
7774            }
7775            return Collections.emptyList();
7776        }
7777    }
7778
7779    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7780            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7781        if (instantAppPkgName == null) {
7782            return resolveInfos;
7783        }
7784        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7785            final ResolveInfo info = resolveInfos.get(i);
7786            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7787            // allow providers that are defined in the provided package
7788            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7789                if (info.providerInfo.splitName != null
7790                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7791                                info.providerInfo.splitName)) {
7792                    // requested provider is defined in a split that hasn't been installed yet.
7793                    // add the installer to the resolve list
7794                    if (DEBUG_INSTANT) {
7795                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7796                    }
7797                    final ResolveInfo installerInfo = new ResolveInfo(
7798                            mInstantAppInstallerInfo);
7799                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7800                            null /*failureActivity*/,
7801                            info.providerInfo.packageName,
7802                            info.providerInfo.applicationInfo.versionCode,
7803                            info.providerInfo.splitName);
7804                    // add a non-generic filter
7805                    installerInfo.filter = new IntentFilter();
7806                    // load resources from the correct package
7807                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7808                    resolveInfos.set(i, installerInfo);
7809                }
7810                continue;
7811            }
7812            // allow providers that have been explicitly exposed to instant applications
7813            if (!isEphemeralApp
7814                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7815                continue;
7816            }
7817            resolveInfos.remove(i);
7818        }
7819        return resolveInfos;
7820    }
7821
7822    @Override
7823    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7824        final int callingUid = Binder.getCallingUid();
7825        if (getInstantAppPackageName(callingUid) != null) {
7826            return ParceledListSlice.emptyList();
7827        }
7828        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7829        flags = updateFlagsForPackage(flags, userId, null);
7830        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7831        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7832                true /* requireFullPermission */, false /* checkShell */,
7833                "get installed packages");
7834
7835        // writer
7836        synchronized (mPackages) {
7837            ArrayList<PackageInfo> list;
7838            if (listUninstalled) {
7839                list = new ArrayList<>(mSettings.mPackages.size());
7840                for (PackageSetting ps : mSettings.mPackages.values()) {
7841                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7842                        continue;
7843                    }
7844                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7845                        continue;
7846                    }
7847                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7848                    if (pi != null) {
7849                        list.add(pi);
7850                    }
7851                }
7852            } else {
7853                list = new ArrayList<>(mPackages.size());
7854                for (PackageParser.Package p : mPackages.values()) {
7855                    final PackageSetting ps = (PackageSetting) p.mExtras;
7856                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7857                        continue;
7858                    }
7859                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7860                        continue;
7861                    }
7862                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7863                            p.mExtras, flags, userId);
7864                    if (pi != null) {
7865                        list.add(pi);
7866                    }
7867                }
7868            }
7869
7870            return new ParceledListSlice<>(list);
7871        }
7872    }
7873
7874    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7875            String[] permissions, boolean[] tmp, int flags, int userId) {
7876        int numMatch = 0;
7877        final PermissionsState permissionsState = ps.getPermissionsState();
7878        for (int i=0; i<permissions.length; i++) {
7879            final String permission = permissions[i];
7880            if (permissionsState.hasPermission(permission, userId)) {
7881                tmp[i] = true;
7882                numMatch++;
7883            } else {
7884                tmp[i] = false;
7885            }
7886        }
7887        if (numMatch == 0) {
7888            return;
7889        }
7890        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7891
7892        // The above might return null in cases of uninstalled apps or install-state
7893        // skew across users/profiles.
7894        if (pi != null) {
7895            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7896                if (numMatch == permissions.length) {
7897                    pi.requestedPermissions = permissions;
7898                } else {
7899                    pi.requestedPermissions = new String[numMatch];
7900                    numMatch = 0;
7901                    for (int i=0; i<permissions.length; i++) {
7902                        if (tmp[i]) {
7903                            pi.requestedPermissions[numMatch] = permissions[i];
7904                            numMatch++;
7905                        }
7906                    }
7907                }
7908            }
7909            list.add(pi);
7910        }
7911    }
7912
7913    @Override
7914    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7915            String[] permissions, int flags, int userId) {
7916        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7917        flags = updateFlagsForPackage(flags, userId, permissions);
7918        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7919                true /* requireFullPermission */, false /* checkShell */,
7920                "get packages holding permissions");
7921        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7922
7923        // writer
7924        synchronized (mPackages) {
7925            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7926            boolean[] tmpBools = new boolean[permissions.length];
7927            if (listUninstalled) {
7928                for (PackageSetting ps : mSettings.mPackages.values()) {
7929                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7930                            userId);
7931                }
7932            } else {
7933                for (PackageParser.Package pkg : mPackages.values()) {
7934                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7935                    if (ps != null) {
7936                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7937                                userId);
7938                    }
7939                }
7940            }
7941
7942            return new ParceledListSlice<PackageInfo>(list);
7943        }
7944    }
7945
7946    @Override
7947    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7948        final int callingUid = Binder.getCallingUid();
7949        if (getInstantAppPackageName(callingUid) != null) {
7950            return ParceledListSlice.emptyList();
7951        }
7952        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7953        flags = updateFlagsForApplication(flags, userId, null);
7954        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7955
7956        // writer
7957        synchronized (mPackages) {
7958            ArrayList<ApplicationInfo> list;
7959            if (listUninstalled) {
7960                list = new ArrayList<>(mSettings.mPackages.size());
7961                for (PackageSetting ps : mSettings.mPackages.values()) {
7962                    ApplicationInfo ai;
7963                    int effectiveFlags = flags;
7964                    if (ps.isSystem()) {
7965                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7966                    }
7967                    if (ps.pkg != null) {
7968                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7969                            continue;
7970                        }
7971                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7972                            continue;
7973                        }
7974                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7975                                ps.readUserState(userId), userId);
7976                        if (ai != null) {
7977                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7978                        }
7979                    } else {
7980                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7981                        // and already converts to externally visible package name
7982                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7983                                callingUid, effectiveFlags, userId);
7984                    }
7985                    if (ai != null) {
7986                        list.add(ai);
7987                    }
7988                }
7989            } else {
7990                list = new ArrayList<>(mPackages.size());
7991                for (PackageParser.Package p : mPackages.values()) {
7992                    if (p.mExtras != null) {
7993                        PackageSetting ps = (PackageSetting) p.mExtras;
7994                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
7995                            continue;
7996                        }
7997                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7998                            continue;
7999                        }
8000                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8001                                ps.readUserState(userId), userId);
8002                        if (ai != null) {
8003                            ai.packageName = resolveExternalPackageNameLPr(p);
8004                            list.add(ai);
8005                        }
8006                    }
8007                }
8008            }
8009
8010            return new ParceledListSlice<>(list);
8011        }
8012    }
8013
8014    @Override
8015    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8016        if (HIDE_EPHEMERAL_APIS) {
8017            return null;
8018        }
8019        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8020            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8021                    "getEphemeralApplications");
8022        }
8023        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8024                true /* requireFullPermission */, false /* checkShell */,
8025                "getEphemeralApplications");
8026        synchronized (mPackages) {
8027            List<InstantAppInfo> instantApps = mInstantAppRegistry
8028                    .getInstantAppsLPr(userId);
8029            if (instantApps != null) {
8030                return new ParceledListSlice<>(instantApps);
8031            }
8032        }
8033        return null;
8034    }
8035
8036    @Override
8037    public boolean isInstantApp(String packageName, int userId) {
8038        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8039                true /* requireFullPermission */, false /* checkShell */,
8040                "isInstantApp");
8041        if (HIDE_EPHEMERAL_APIS) {
8042            return false;
8043        }
8044
8045        synchronized (mPackages) {
8046            int callingUid = Binder.getCallingUid();
8047            if (Process.isIsolated(callingUid)) {
8048                callingUid = mIsolatedOwners.get(callingUid);
8049            }
8050            final PackageSetting ps = mSettings.mPackages.get(packageName);
8051            PackageParser.Package pkg = mPackages.get(packageName);
8052            final boolean returnAllowed =
8053                    ps != null
8054                    && (isCallerSameApp(packageName, callingUid)
8055                            || canViewInstantApps(callingUid, userId)
8056                            || mInstantAppRegistry.isInstantAccessGranted(
8057                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8058            if (returnAllowed) {
8059                return ps.getInstantApp(userId);
8060            }
8061        }
8062        return false;
8063    }
8064
8065    @Override
8066    public byte[] getInstantAppCookie(String packageName, int userId) {
8067        if (HIDE_EPHEMERAL_APIS) {
8068            return null;
8069        }
8070
8071        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8072                true /* requireFullPermission */, false /* checkShell */,
8073                "getInstantAppCookie");
8074        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8075            return null;
8076        }
8077        synchronized (mPackages) {
8078            return mInstantAppRegistry.getInstantAppCookieLPw(
8079                    packageName, userId);
8080        }
8081    }
8082
8083    @Override
8084    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8085        if (HIDE_EPHEMERAL_APIS) {
8086            return true;
8087        }
8088
8089        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8090                true /* requireFullPermission */, true /* checkShell */,
8091                "setInstantAppCookie");
8092        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8093            return false;
8094        }
8095        synchronized (mPackages) {
8096            return mInstantAppRegistry.setInstantAppCookieLPw(
8097                    packageName, cookie, userId);
8098        }
8099    }
8100
8101    @Override
8102    public Bitmap getInstantAppIcon(String packageName, int userId) {
8103        if (HIDE_EPHEMERAL_APIS) {
8104            return null;
8105        }
8106
8107        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8108            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8109                    "getInstantAppIcon");
8110        }
8111        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8112                true /* requireFullPermission */, false /* checkShell */,
8113                "getInstantAppIcon");
8114
8115        synchronized (mPackages) {
8116            return mInstantAppRegistry.getInstantAppIconLPw(
8117                    packageName, userId);
8118        }
8119    }
8120
8121    private boolean isCallerSameApp(String packageName, int uid) {
8122        PackageParser.Package pkg = mPackages.get(packageName);
8123        return pkg != null
8124                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8125    }
8126
8127    @Override
8128    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8129        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8130            return ParceledListSlice.emptyList();
8131        }
8132        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8133    }
8134
8135    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8136        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8137
8138        // reader
8139        synchronized (mPackages) {
8140            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8141            final int userId = UserHandle.getCallingUserId();
8142            while (i.hasNext()) {
8143                final PackageParser.Package p = i.next();
8144                if (p.applicationInfo == null) continue;
8145
8146                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8147                        && !p.applicationInfo.isDirectBootAware();
8148                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8149                        && p.applicationInfo.isDirectBootAware();
8150
8151                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8152                        && (!mSafeMode || isSystemApp(p))
8153                        && (matchesUnaware || matchesAware)) {
8154                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8155                    if (ps != null) {
8156                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8157                                ps.readUserState(userId), userId);
8158                        if (ai != null) {
8159                            finalList.add(ai);
8160                        }
8161                    }
8162                }
8163            }
8164        }
8165
8166        return finalList;
8167    }
8168
8169    @Override
8170    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8171        return resolveContentProviderInternal(name, flags, userId);
8172    }
8173
8174    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
8175        if (!sUserManager.exists(userId)) return null;
8176        flags = updateFlagsForComponent(flags, userId, name);
8177        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8178        // reader
8179        synchronized (mPackages) {
8180            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8181            PackageSetting ps = provider != null
8182                    ? mSettings.mPackages.get(provider.owner.packageName)
8183                    : null;
8184            if (ps != null) {
8185                final boolean isInstantApp = ps.getInstantApp(userId);
8186                // normal application; filter out instant application provider
8187                if (instantAppPkgName == null && isInstantApp) {
8188                    return null;
8189                }
8190                // instant application; filter out other instant applications
8191                if (instantAppPkgName != null
8192                        && isInstantApp
8193                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8194                    return null;
8195                }
8196                // instant application; filter out non-exposed provider
8197                if (instantAppPkgName != null
8198                        && !isInstantApp
8199                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8200                    return null;
8201                }
8202                // provider not enabled
8203                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8204                    return null;
8205                }
8206                return PackageParser.generateProviderInfo(
8207                        provider, flags, ps.readUserState(userId), userId);
8208            }
8209            return null;
8210        }
8211    }
8212
8213    /**
8214     * @deprecated
8215     */
8216    @Deprecated
8217    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8218        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8219            return;
8220        }
8221        // reader
8222        synchronized (mPackages) {
8223            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8224                    .entrySet().iterator();
8225            final int userId = UserHandle.getCallingUserId();
8226            while (i.hasNext()) {
8227                Map.Entry<String, PackageParser.Provider> entry = i.next();
8228                PackageParser.Provider p = entry.getValue();
8229                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8230
8231                if (ps != null && p.syncable
8232                        && (!mSafeMode || (p.info.applicationInfo.flags
8233                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8234                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8235                            ps.readUserState(userId), userId);
8236                    if (info != null) {
8237                        outNames.add(entry.getKey());
8238                        outInfo.add(info);
8239                    }
8240                }
8241            }
8242        }
8243    }
8244
8245    @Override
8246    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8247            int uid, int flags, String metaDataKey) {
8248        final int callingUid = Binder.getCallingUid();
8249        final int userId = processName != null ? UserHandle.getUserId(uid)
8250                : UserHandle.getCallingUserId();
8251        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8252        flags = updateFlagsForComponent(flags, userId, processName);
8253        ArrayList<ProviderInfo> finalList = null;
8254        // reader
8255        synchronized (mPackages) {
8256            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8257            while (i.hasNext()) {
8258                final PackageParser.Provider p = i.next();
8259                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8260                if (ps != null && p.info.authority != null
8261                        && (processName == null
8262                                || (p.info.processName.equals(processName)
8263                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8264                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8265
8266                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8267                    // parameter.
8268                    if (metaDataKey != null
8269                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8270                        continue;
8271                    }
8272                    final ComponentName component =
8273                            new ComponentName(p.info.packageName, p.info.name);
8274                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8275                        continue;
8276                    }
8277                    if (finalList == null) {
8278                        finalList = new ArrayList<ProviderInfo>(3);
8279                    }
8280                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8281                            ps.readUserState(userId), userId);
8282                    if (info != null) {
8283                        finalList.add(info);
8284                    }
8285                }
8286            }
8287        }
8288
8289        if (finalList != null) {
8290            Collections.sort(finalList, mProviderInitOrderSorter);
8291            return new ParceledListSlice<ProviderInfo>(finalList);
8292        }
8293
8294        return ParceledListSlice.emptyList();
8295    }
8296
8297    @Override
8298    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8299        // reader
8300        synchronized (mPackages) {
8301            final int callingUid = Binder.getCallingUid();
8302            final int callingUserId = UserHandle.getUserId(callingUid);
8303            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8304            if (ps == null) return null;
8305            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8306                return null;
8307            }
8308            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8309            return PackageParser.generateInstrumentationInfo(i, flags);
8310        }
8311    }
8312
8313    @Override
8314    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8315            String targetPackage, int flags) {
8316        final int callingUid = Binder.getCallingUid();
8317        final int callingUserId = UserHandle.getUserId(callingUid);
8318        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8319        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8320            return ParceledListSlice.emptyList();
8321        }
8322        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8323    }
8324
8325    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8326            int flags) {
8327        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8328
8329        // reader
8330        synchronized (mPackages) {
8331            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8332            while (i.hasNext()) {
8333                final PackageParser.Instrumentation p = i.next();
8334                if (targetPackage == null
8335                        || targetPackage.equals(p.info.targetPackage)) {
8336                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8337                            flags);
8338                    if (ii != null) {
8339                        finalList.add(ii);
8340                    }
8341                }
8342            }
8343        }
8344
8345        return finalList;
8346    }
8347
8348    private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) {
8349        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]");
8350        try {
8351            scanDirLI(scanDir, parseFlags, scanFlags, currentTime);
8352        } finally {
8353            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8354        }
8355    }
8356
8357    private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) {
8358        final File[] files = scanDir.listFiles();
8359        if (ArrayUtils.isEmpty(files)) {
8360            Log.d(TAG, "No files in app dir " + scanDir);
8361            return;
8362        }
8363
8364        if (DEBUG_PACKAGE_SCANNING) {
8365            Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags
8366                    + " flags=0x" + Integer.toHexString(parseFlags));
8367        }
8368        try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8369                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8370                mParallelPackageParserCallback)) {
8371            // Submit files for parsing in parallel
8372            int fileCount = 0;
8373            for (File file : files) {
8374                final boolean isPackage = (isApkFile(file) || file.isDirectory())
8375                        && !PackageInstallerService.isStageName(file.getName());
8376                if (!isPackage) {
8377                    // Ignore entries which are not packages
8378                    continue;
8379                }
8380                parallelPackageParser.submit(file, parseFlags);
8381                fileCount++;
8382            }
8383
8384            // Process results one by one
8385            for (; fileCount > 0; fileCount--) {
8386                ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8387                Throwable throwable = parseResult.throwable;
8388                int errorCode = PackageManager.INSTALL_SUCCEEDED;
8389
8390                if (throwable == null) {
8391                    // TODO(toddke): move lower in the scan chain
8392                    // Static shared libraries have synthetic package names
8393                    if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8394                        renameStaticSharedLibraryPackage(parseResult.pkg);
8395                    }
8396                    try {
8397                        if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8398                            scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags,
8399                                    currentTime, null);
8400                        }
8401                    } catch (PackageManagerException e) {
8402                        errorCode = e.error;
8403                        Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8404                    }
8405                } else if (throwable instanceof PackageParser.PackageParserException) {
8406                    PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8407                            throwable;
8408                    errorCode = e.error;
8409                    Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8410                } else {
8411                    throw new IllegalStateException("Unexpected exception occurred while parsing "
8412                            + parseResult.scanFile, throwable);
8413                }
8414
8415                // Delete invalid userdata apps
8416                if ((scanFlags & SCAN_AS_SYSTEM) == 0 &&
8417                        errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8418                    logCriticalInfo(Log.WARN,
8419                            "Deleting invalid package at " + parseResult.scanFile);
8420                    removeCodePathLI(parseResult.scanFile);
8421                }
8422            }
8423        }
8424    }
8425
8426    public static void reportSettingsProblem(int priority, String msg) {
8427        logCriticalInfo(priority, msg);
8428    }
8429
8430    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg,
8431            boolean forceCollect, boolean skipVerify) throws PackageManagerException {
8432        // When upgrading from pre-N MR1, verify the package time stamp using the package
8433        // directory and not the APK file.
8434        final long lastModifiedTime = mIsPreNMR1Upgrade
8435                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg);
8436        if (ps != null && !forceCollect
8437                && ps.codePathString.equals(pkg.codePath)
8438                && ps.timeStamp == lastModifiedTime
8439                && !isCompatSignatureUpdateNeeded(pkg)
8440                && !isRecoverSignatureUpdateNeeded(pkg)) {
8441            if (ps.signatures.mSigningDetails.signatures != null
8442                    && ps.signatures.mSigningDetails.signatures.length != 0
8443                    && ps.signatures.mSigningDetails.signatureSchemeVersion
8444                            != SignatureSchemeVersion.UNKNOWN) {
8445                // Optimization: reuse the existing cached signing data
8446                // if the package appears to be unchanged.
8447                pkg.mSigningDetails =
8448                        new PackageParser.SigningDetails(ps.signatures.mSigningDetails);
8449                return;
8450            }
8451
8452            Slog.w(TAG, "PackageSetting for " + ps.name
8453                    + " is missing signatures.  Collecting certs again to recover them.");
8454        } else {
8455            Slog.i(TAG, pkg.codePath + " changed; collecting certs" +
8456                    (forceCollect ? " (forced)" : ""));
8457        }
8458
8459        try {
8460            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8461            PackageParser.collectCertificates(pkg, skipVerify);
8462        } catch (PackageParserException e) {
8463            throw PackageManagerException.from(e);
8464        } finally {
8465            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8466        }
8467    }
8468
8469    /**
8470     *  Traces a package scan.
8471     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8472     */
8473    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8474            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8475        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8476        try {
8477            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8478        } finally {
8479            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8480        }
8481    }
8482
8483    /**
8484     *  Scans a package and returns the newly parsed package.
8485     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8486     */
8487    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8488            long currentTime, UserHandle user) throws PackageManagerException {
8489        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8490        PackageParser pp = new PackageParser();
8491        pp.setSeparateProcesses(mSeparateProcesses);
8492        pp.setOnlyCoreApps(mOnlyCore);
8493        pp.setDisplayMetrics(mMetrics);
8494        pp.setCallback(mPackageParserCallback);
8495
8496        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8497        final PackageParser.Package pkg;
8498        try {
8499            pkg = pp.parsePackage(scanFile, parseFlags);
8500        } catch (PackageParserException e) {
8501            throw PackageManagerException.from(e);
8502        } finally {
8503            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8504        }
8505
8506        // Static shared libraries have synthetic package names
8507        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8508            renameStaticSharedLibraryPackage(pkg);
8509        }
8510
8511        return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8512    }
8513
8514    /**
8515     *  Scans a package and returns the newly parsed package.
8516     *  @throws PackageManagerException on a parse error.
8517     */
8518    private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg,
8519            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8520            @Nullable UserHandle user)
8521                    throws PackageManagerException {
8522        // If the package has children and this is the first dive in the function
8523        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8524        // packages (parent and children) would be successfully scanned before the
8525        // actual scan since scanning mutates internal state and we want to atomically
8526        // install the package and its children.
8527        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8528            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8529                scanFlags |= SCAN_CHECK_ONLY;
8530            }
8531        } else {
8532            scanFlags &= ~SCAN_CHECK_ONLY;
8533        }
8534
8535        // Scan the parent
8536        PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags,
8537                scanFlags, currentTime, user);
8538
8539        // Scan the children
8540        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8541        for (int i = 0; i < childCount; i++) {
8542            PackageParser.Package childPackage = pkg.childPackages.get(i);
8543            addForInitLI(childPackage, parseFlags, scanFlags,
8544                    currentTime, user);
8545        }
8546
8547
8548        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8549            return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8550        }
8551
8552        return scannedPkg;
8553    }
8554
8555    /**
8556     * Returns if full apk verification can be skipped for the whole package, including the splits.
8557     */
8558    private boolean canSkipFullPackageVerification(PackageParser.Package pkg) {
8559        if (!canSkipFullApkVerification(pkg.baseCodePath)) {
8560            return false;
8561        }
8562        // TODO: Allow base and splits to be verified individually.
8563        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8564            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8565                if (!canSkipFullApkVerification(pkg.splitCodePaths[i])) {
8566                    return false;
8567                }
8568            }
8569        }
8570        return true;
8571    }
8572
8573    /**
8574     * Returns if full apk verification can be skipped, depending on current FSVerity setup and
8575     * whether the apk contains signed root hash.  Note that the signer's certificate still needs to
8576     * match one in a trusted source, and should be done separately.
8577     */
8578    private boolean canSkipFullApkVerification(String apkPath) {
8579        byte[] rootHashObserved = null;
8580        try {
8581            rootHashObserved = VerityUtils.generateFsverityRootHash(apkPath);
8582            if (rootHashObserved == null) {
8583                return false;  // APK does not contain Merkle tree root hash.
8584            }
8585            synchronized (mInstallLock) {
8586                // Returns whether the observed root hash matches what kernel has.
8587                mInstaller.assertFsverityRootHashMatches(apkPath, rootHashObserved);
8588                return true;
8589            }
8590        } catch (InstallerException | IOException | DigestException |
8591                NoSuchAlgorithmException e) {
8592            Slog.w(TAG, "Error in fsverity check. Fallback to full apk verification.", e);
8593        }
8594        return false;
8595    }
8596
8597    /**
8598     * Adds a new package to the internal data structures during platform initialization.
8599     * <p>After adding, the package is known to the system and available for querying.
8600     * <p>For packages located on the device ROM [eg. packages located in /system, /vendor,
8601     * etc...], additional checks are performed. Basic verification [such as ensuring
8602     * matching signatures, checking version codes, etc...] occurs if the package is
8603     * identical to a previously known package. If the package fails a signature check,
8604     * the version installed on /data will be removed. If the version of the new package
8605     * is less than or equal than the version on /data, it will be ignored.
8606     * <p>Regardless of the package location, the results are applied to the internal
8607     * structures and the package is made available to the rest of the system.
8608     * <p>NOTE: The return value should be removed. It's the passed in package object.
8609     */
8610    private PackageParser.Package addForInitLI(PackageParser.Package pkg,
8611            @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8612            @Nullable UserHandle user)
8613                    throws PackageManagerException {
8614        final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0;
8615        final String renamedPkgName;
8616        final PackageSetting disabledPkgSetting;
8617        final boolean isSystemPkgUpdated;
8618        final boolean pkgAlreadyExists;
8619        PackageSetting pkgSetting;
8620
8621        // NOTE: installPackageLI() has the same code to setup the package's
8622        // application info. This probably should be done lower in the call
8623        // stack [such as scanPackageOnly()]. However, we verify the application
8624        // info prior to that [in scanPackageNew()] and thus have to setup
8625        // the application info early.
8626        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8627        pkg.setApplicationInfoCodePath(pkg.codePath);
8628        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8629        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8630        pkg.setApplicationInfoResourcePath(pkg.codePath);
8631        pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
8632        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8633
8634        synchronized (mPackages) {
8635            renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8636            final String realPkgName = getRealPackageName(pkg, renamedPkgName);
8637            if (realPkgName != null) {
8638                ensurePackageRenamed(pkg, renamedPkgName);
8639            }
8640            final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
8641            final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName);
8642            pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting;
8643            pkgAlreadyExists = pkgSetting != null;
8644            final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName;
8645            disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName);
8646            isSystemPkgUpdated = disabledPkgSetting != null;
8647
8648            if (DEBUG_INSTALL && isSystemPkgUpdated) {
8649                Slog.d(TAG, "updatedPkg = " + disabledPkgSetting);
8650            }
8651
8652            final SharedUserSetting sharedUserSetting = (pkg.mSharedUserId != null)
8653                    ? mSettings.getSharedUserLPw(pkg.mSharedUserId,
8654                            0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true)
8655                    : null;
8656            if (DEBUG_PACKAGE_SCANNING
8657                    && (parseFlags & PackageParser.PARSE_CHATTY) != 0
8658                    && sharedUserSetting != null) {
8659                Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
8660                        + " (uid=" + sharedUserSetting.userId + "):"
8661                        + " packages=" + sharedUserSetting.packages);
8662            }
8663
8664            if (scanSystemPartition) {
8665                // Potentially prune child packages. If the application on the /system
8666                // partition has been updated via OTA, but, is still disabled by a
8667                // version on /data, cycle through all of its children packages and
8668                // remove children that are no longer defined.
8669                if (isSystemPkgUpdated) {
8670                    final int scannedChildCount = (pkg.childPackages != null)
8671                            ? pkg.childPackages.size() : 0;
8672                    final int disabledChildCount = disabledPkgSetting.childPackageNames != null
8673                            ? disabledPkgSetting.childPackageNames.size() : 0;
8674                    for (int i = 0; i < disabledChildCount; i++) {
8675                        String disabledChildPackageName =
8676                                disabledPkgSetting.childPackageNames.get(i);
8677                        boolean disabledPackageAvailable = false;
8678                        for (int j = 0; j < scannedChildCount; j++) {
8679                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8680                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8681                                disabledPackageAvailable = true;
8682                                break;
8683                            }
8684                        }
8685                        if (!disabledPackageAvailable) {
8686                            mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8687                        }
8688                    }
8689                    // we're updating the disabled package, so, scan it as the package setting
8690                    final ScanRequest request = new ScanRequest(pkg, sharedUserSetting,
8691                            disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */,
8692                            null /* originalPkgSetting */, null, parseFlags, scanFlags,
8693                            (pkg == mPlatformPackage), user);
8694                    applyPolicy(pkg, parseFlags, scanFlags);
8695                    scanPackageOnlyLI(request, mFactoryTest, -1L);
8696                }
8697            }
8698        }
8699
8700        final boolean newPkgChangedPaths =
8701                pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath);
8702        final boolean newPkgVersionGreater =
8703                pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode;
8704        final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated
8705                && newPkgChangedPaths && newPkgVersionGreater;
8706        if (isSystemPkgBetter) {
8707            // The version of the application on /system is greater than the version on
8708            // /data. Switch back to the application on /system.
8709            // It's safe to assume the application on /system will correctly scan. If not,
8710            // there won't be a working copy of the application.
8711            synchronized (mPackages) {
8712                // just remove the loaded entries from package lists
8713                mPackages.remove(pkgSetting.name);
8714            }
8715
8716            logCriticalInfo(Log.WARN,
8717                    "System package updated;"
8718                    + " name: " + pkgSetting.name
8719                    + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8720                    + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8721
8722            final InstallArgs args = createInstallArgsForExisting(
8723                    packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8724                    pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8725            args.cleanUpResourcesLI();
8726            synchronized (mPackages) {
8727                mSettings.enableSystemPackageLPw(pkgSetting.name);
8728            }
8729        }
8730
8731        if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) {
8732            // The version of the application on the /system partition is less than or
8733            // equal to the version on the /data partition. Throw an exception and use
8734            // the application already installed on the /data partition.
8735            throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at "
8736                    + pkg.codePath + " ignored: updated version " + disabledPkgSetting.versionCode
8737                    + " better than this " + pkg.getLongVersionCode());
8738        }
8739
8740        // Verify certificates against what was last scanned. If it is an updated priv app, we will
8741        // force re-collecting certificate.
8742        final boolean forceCollect = PackageManagerServiceUtils.isApkVerificationForced(
8743                disabledPkgSetting);
8744        // Full APK verification can be skipped during certificate collection, only if the file is
8745        // in verified partition, or can be verified on access (when apk verity is enabled). In both
8746        // cases, only data in Signing Block is verified instead of the whole file.
8747        final boolean skipVerify = ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) ||
8748                (forceCollect && canSkipFullPackageVerification(pkg));
8749        collectCertificatesLI(pkgSetting, pkg, forceCollect, skipVerify);
8750
8751        boolean shouldHideSystemApp = false;
8752        // A new application appeared on /system, but, we already have a copy of
8753        // the application installed on /data.
8754        if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists
8755                && !pkgSetting.isSystem()) {
8756
8757            if (!pkg.mSigningDetails.checkCapability(pkgSetting.signatures.mSigningDetails,
8758                    PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)) {
8759                logCriticalInfo(Log.WARN,
8760                        "System package signature mismatch;"
8761                        + " name: " + pkgSetting.name);
8762                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8763                        "scanPackageInternalLI")) {
8764                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8765                }
8766                pkgSetting = null;
8767            } else if (newPkgVersionGreater) {
8768                // The application on /system is newer than the application on /data.
8769                // Simply remove the application on /data [keeping application data]
8770                // and replace it with the version on /system.
8771                logCriticalInfo(Log.WARN,
8772                        "System package enabled;"
8773                        + " name: " + pkgSetting.name
8774                        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8775                        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8776                InstallArgs args = createInstallArgsForExisting(
8777                        packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8778                        pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8779                synchronized (mInstallLock) {
8780                    args.cleanUpResourcesLI();
8781                }
8782            } else {
8783                // The application on /system is older than the application on /data. Hide
8784                // the application on /system and the version on /data will be scanned later
8785                // and re-added like an update.
8786                shouldHideSystemApp = true;
8787                logCriticalInfo(Log.INFO,
8788                        "System package disabled;"
8789                        + " name: " + pkgSetting.name
8790                        + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode
8791                        + "; new: " + pkg.codePath + " @ " + pkg.codePath);
8792            }
8793        }
8794
8795        final PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags
8796                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8797
8798        if (shouldHideSystemApp) {
8799            synchronized (mPackages) {
8800                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8801            }
8802        }
8803        return scannedPkg;
8804    }
8805
8806    private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8807        // Derive the new package synthetic package name
8808        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8809                + pkg.staticSharedLibVersion);
8810    }
8811
8812    private static String fixProcessName(String defProcessName,
8813            String processName) {
8814        if (processName == null) {
8815            return defProcessName;
8816        }
8817        return processName;
8818    }
8819
8820    /**
8821     * Enforces that only the system UID or root's UID can call a method exposed
8822     * via Binder.
8823     *
8824     * @param message used as message if SecurityException is thrown
8825     * @throws SecurityException if the caller is not system or root
8826     */
8827    private static final void enforceSystemOrRoot(String message) {
8828        final int uid = Binder.getCallingUid();
8829        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8830            throw new SecurityException(message);
8831        }
8832    }
8833
8834    @Override
8835    public void performFstrimIfNeeded() {
8836        enforceSystemOrRoot("Only the system can request fstrim");
8837
8838        // Before everything else, see whether we need to fstrim.
8839        try {
8840            IStorageManager sm = PackageHelper.getStorageManager();
8841            if (sm != null) {
8842                boolean doTrim = false;
8843                final long interval = android.provider.Settings.Global.getLong(
8844                        mContext.getContentResolver(),
8845                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8846                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8847                if (interval > 0) {
8848                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8849                    if (timeSinceLast > interval) {
8850                        doTrim = true;
8851                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8852                                + "; running immediately");
8853                    }
8854                }
8855                if (doTrim) {
8856                    final boolean dexOptDialogShown;
8857                    synchronized (mPackages) {
8858                        dexOptDialogShown = mDexOptDialogShown;
8859                    }
8860                    if (!isFirstBoot() && dexOptDialogShown) {
8861                        try {
8862                            ActivityManager.getService().showBootMessage(
8863                                    mContext.getResources().getString(
8864                                            R.string.android_upgrading_fstrim), true);
8865                        } catch (RemoteException e) {
8866                        }
8867                    }
8868                    sm.runMaintenance();
8869                }
8870            } else {
8871                Slog.e(TAG, "storageManager service unavailable!");
8872            }
8873        } catch (RemoteException e) {
8874            // Can't happen; StorageManagerService is local
8875        }
8876    }
8877
8878    @Override
8879    public void updatePackagesIfNeeded() {
8880        enforceSystemOrRoot("Only the system can request package update");
8881
8882        // We need to re-extract after an OTA.
8883        boolean causeUpgrade = isUpgrade();
8884
8885        // First boot or factory reset.
8886        // Note: we also handle devices that are upgrading to N right now as if it is their
8887        //       first boot, as they do not have profile data.
8888        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8889
8890        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8891        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8892
8893        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8894            return;
8895        }
8896
8897        List<PackageParser.Package> pkgs;
8898        synchronized (mPackages) {
8899            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8900        }
8901
8902        final long startTime = System.nanoTime();
8903        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8904                    causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT,
8905                    false /* bootComplete */);
8906
8907        final int elapsedTimeSeconds =
8908                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8909
8910        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8911        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8912        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8913        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8914        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8915    }
8916
8917    /*
8918     * Return the prebuilt profile path given a package base code path.
8919     */
8920    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
8921        return pkg.baseCodePath + ".prof";
8922    }
8923
8924    /**
8925     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8926     * containing statistics about the invocation. The array consists of three elements,
8927     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8928     * and {@code numberOfPackagesFailed}.
8929     */
8930    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8931            final int compilationReason, boolean bootComplete) {
8932
8933        int numberOfPackagesVisited = 0;
8934        int numberOfPackagesOptimized = 0;
8935        int numberOfPackagesSkipped = 0;
8936        int numberOfPackagesFailed = 0;
8937        final int numberOfPackagesToDexopt = pkgs.size();
8938
8939        for (PackageParser.Package pkg : pkgs) {
8940            numberOfPackagesVisited++;
8941
8942            boolean useProfileForDexopt = false;
8943
8944            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
8945                // Copy over initial preopt profiles since we won't get any JIT samples for methods
8946                // that are already compiled.
8947                File profileFile = new File(getPrebuildProfilePath(pkg));
8948                // Copy profile if it exists.
8949                if (profileFile.exists()) {
8950                    try {
8951                        // We could also do this lazily before calling dexopt in
8952                        // PackageDexOptimizer to prevent this happening on first boot. The issue
8953                        // is that we don't have a good way to say "do this only once".
8954                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8955                                pkg.applicationInfo.uid, pkg.packageName,
8956                                ArtManager.getProfileName(null))) {
8957                            Log.e(TAG, "Installer failed to copy system profile!");
8958                        } else {
8959                            // Disabled as this causes speed-profile compilation during first boot
8960                            // even if things are already compiled.
8961                            // useProfileForDexopt = true;
8962                        }
8963                    } catch (Exception e) {
8964                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
8965                                e);
8966                    }
8967                } else {
8968                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8969                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
8970                    // minimize the number off apps being speed-profile compiled during first boot.
8971                    // The other paths will not change the filter.
8972                    if (disabledPs != null && disabledPs.pkg.isStub) {
8973                        // The package is the stub one, remove the stub suffix to get the normal
8974                        // package and APK names.
8975                        String systemProfilePath =
8976                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
8977                        profileFile = new File(systemProfilePath);
8978                        // If we have a profile for a compressed APK, copy it to the reference
8979                        // location.
8980                        // Note that copying the profile here will cause it to override the
8981                        // reference profile every OTA even though the existing reference profile
8982                        // may have more data. We can't copy during decompression since the
8983                        // directories are not set up at that point.
8984                        if (profileFile.exists()) {
8985                            try {
8986                                // We could also do this lazily before calling dexopt in
8987                                // PackageDexOptimizer to prevent this happening on first boot. The
8988                                // issue is that we don't have a good way to say "do this only
8989                                // once".
8990                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8991                                        pkg.applicationInfo.uid, pkg.packageName,
8992                                        ArtManager.getProfileName(null))) {
8993                                    Log.e(TAG, "Failed to copy system profile for stub package!");
8994                                } else {
8995                                    useProfileForDexopt = true;
8996                                }
8997                            } catch (Exception e) {
8998                                Log.e(TAG, "Failed to copy profile " +
8999                                        profileFile.getAbsolutePath() + " ", e);
9000                            }
9001                        }
9002                    }
9003                }
9004            }
9005
9006            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9007                if (DEBUG_DEXOPT) {
9008                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9009                }
9010                numberOfPackagesSkipped++;
9011                continue;
9012            }
9013
9014            if (DEBUG_DEXOPT) {
9015                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9016                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9017            }
9018
9019            if (showDialog) {
9020                try {
9021                    ActivityManager.getService().showBootMessage(
9022                            mContext.getResources().getString(R.string.android_upgrading_apk,
9023                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9024                } catch (RemoteException e) {
9025                }
9026                synchronized (mPackages) {
9027                    mDexOptDialogShown = true;
9028                }
9029            }
9030
9031            int pkgCompilationReason = compilationReason;
9032            if (useProfileForDexopt) {
9033                // Use background dexopt mode to try and use the profile. Note that this does not
9034                // guarantee usage of the profile.
9035                pkgCompilationReason = PackageManagerService.REASON_BACKGROUND_DEXOPT;
9036            }
9037
9038            // checkProfiles is false to avoid merging profiles during boot which
9039            // might interfere with background compilation (b/28612421).
9040            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9041            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9042            // trade-off worth doing to save boot time work.
9043            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9044            if (compilationReason == REASON_FIRST_BOOT) {
9045                // TODO: This doesn't cover the upgrade case, we should check for this too.
9046                dexoptFlags |= DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE;
9047            }
9048            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9049                    pkg.packageName,
9050                    pkgCompilationReason,
9051                    dexoptFlags));
9052
9053            switch (primaryDexOptStaus) {
9054                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9055                    numberOfPackagesOptimized++;
9056                    break;
9057                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9058                    numberOfPackagesSkipped++;
9059                    break;
9060                case PackageDexOptimizer.DEX_OPT_FAILED:
9061                    numberOfPackagesFailed++;
9062                    break;
9063                default:
9064                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9065                    break;
9066            }
9067        }
9068
9069        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9070                numberOfPackagesFailed };
9071    }
9072
9073    @Override
9074    public void notifyPackageUse(String packageName, int reason) {
9075        synchronized (mPackages) {
9076            final int callingUid = Binder.getCallingUid();
9077            final int callingUserId = UserHandle.getUserId(callingUid);
9078            if (getInstantAppPackageName(callingUid) != null) {
9079                if (!isCallerSameApp(packageName, callingUid)) {
9080                    return;
9081                }
9082            } else {
9083                if (isInstantApp(packageName, callingUserId)) {
9084                    return;
9085                }
9086            }
9087            notifyPackageUseLocked(packageName, reason);
9088        }
9089    }
9090
9091    @GuardedBy("mPackages")
9092    private void notifyPackageUseLocked(String packageName, int reason) {
9093        final PackageParser.Package p = mPackages.get(packageName);
9094        if (p == null) {
9095            return;
9096        }
9097        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9098    }
9099
9100    @Override
9101    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9102            List<String> classPaths, String loaderIsa) {
9103        int userId = UserHandle.getCallingUserId();
9104        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9105        if (ai == null) {
9106            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9107                + loadingPackageName + ", user=" + userId);
9108            return;
9109        }
9110        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9111    }
9112
9113    @Override
9114    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9115            IDexModuleRegisterCallback callback) {
9116        int userId = UserHandle.getCallingUserId();
9117        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9118        DexManager.RegisterDexModuleResult result;
9119        if (ai == null) {
9120            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9121                     " calling user. package=" + packageName + ", user=" + userId);
9122            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9123        } else {
9124            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9125        }
9126
9127        if (callback != null) {
9128            mHandler.post(() -> {
9129                try {
9130                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9131                } catch (RemoteException e) {
9132                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9133                }
9134            });
9135        }
9136    }
9137
9138    /**
9139     * Ask the package manager to perform a dex-opt with the given compiler filter.
9140     *
9141     * Note: exposed only for the shell command to allow moving packages explicitly to a
9142     *       definite state.
9143     */
9144    @Override
9145    public boolean performDexOptMode(String packageName,
9146            boolean checkProfiles, String targetCompilerFilter, boolean force,
9147            boolean bootComplete, String splitName) {
9148        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9149                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9150                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9151        return performDexOpt(new DexoptOptions(packageName, REASON_UNKNOWN,
9152                targetCompilerFilter, splitName, flags));
9153    }
9154
9155    /**
9156     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9157     * secondary dex files belonging to the given package.
9158     *
9159     * Note: exposed only for the shell command to allow moving packages explicitly to a
9160     *       definite state.
9161     */
9162    @Override
9163    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9164            boolean force) {
9165        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9166                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9167                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9168                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9169        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9170    }
9171
9172    /*package*/ boolean performDexOpt(DexoptOptions options) {
9173        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9174            return false;
9175        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9176            return false;
9177        }
9178
9179        if (options.isDexoptOnlySecondaryDex()) {
9180            return mDexManager.dexoptSecondaryDex(options);
9181        } else {
9182            int dexoptStatus = performDexOptWithStatus(options);
9183            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9184        }
9185    }
9186
9187    /**
9188     * Perform dexopt on the given package and return one of following result:
9189     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9190     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9191     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9192     */
9193    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9194        return performDexOptTraced(options);
9195    }
9196
9197    private int performDexOptTraced(DexoptOptions options) {
9198        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9199        try {
9200            return performDexOptInternal(options);
9201        } finally {
9202            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9203        }
9204    }
9205
9206    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9207    // if the package can now be considered up to date for the given filter.
9208    private int performDexOptInternal(DexoptOptions options) {
9209        PackageParser.Package p;
9210        synchronized (mPackages) {
9211            p = mPackages.get(options.getPackageName());
9212            if (p == null) {
9213                // Package could not be found. Report failure.
9214                return PackageDexOptimizer.DEX_OPT_FAILED;
9215            }
9216            mPackageUsage.maybeWriteAsync(mPackages);
9217            mCompilerStats.maybeWriteAsync();
9218        }
9219        long callingId = Binder.clearCallingIdentity();
9220        try {
9221            synchronized (mInstallLock) {
9222                return performDexOptInternalWithDependenciesLI(p, options);
9223            }
9224        } finally {
9225            Binder.restoreCallingIdentity(callingId);
9226        }
9227    }
9228
9229    public ArraySet<String> getOptimizablePackages() {
9230        ArraySet<String> pkgs = new ArraySet<String>();
9231        synchronized (mPackages) {
9232            for (PackageParser.Package p : mPackages.values()) {
9233                if (PackageDexOptimizer.canOptimizePackage(p)) {
9234                    pkgs.add(p.packageName);
9235                }
9236            }
9237        }
9238        return pkgs;
9239    }
9240
9241    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9242            DexoptOptions options) {
9243        // Select the dex optimizer based on the force parameter.
9244        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9245        //       allocate an object here.
9246        PackageDexOptimizer pdo = options.isForce()
9247                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9248                : mPackageDexOptimizer;
9249
9250        // Dexopt all dependencies first. Note: we ignore the return value and march on
9251        // on errors.
9252        // Note that we are going to call performDexOpt on those libraries as many times as
9253        // they are referenced in packages. When we do a batch of performDexOpt (for example
9254        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9255        // and the first package that uses the library will dexopt it. The
9256        // others will see that the compiled code for the library is up to date.
9257        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9258        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9259        if (!deps.isEmpty()) {
9260            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9261                    options.getCompilationReason(), options.getCompilerFilter(),
9262                    options.getSplitName(),
9263                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9264            for (PackageParser.Package depPackage : deps) {
9265                // TODO: Analyze and investigate if we (should) profile libraries.
9266                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9267                        getOrCreateCompilerPackageStats(depPackage),
9268                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9269            }
9270        }
9271        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9272                getOrCreateCompilerPackageStats(p),
9273                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9274    }
9275
9276    /**
9277     * Reconcile the information we have about the secondary dex files belonging to
9278     * {@code packagName} and the actual dex files. For all dex files that were
9279     * deleted, update the internal records and delete the generated oat files.
9280     */
9281    @Override
9282    public void reconcileSecondaryDexFiles(String packageName) {
9283        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9284            return;
9285        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9286            return;
9287        }
9288        mDexManager.reconcileSecondaryDexFiles(packageName);
9289    }
9290
9291    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9292    // a reference there.
9293    /*package*/ DexManager getDexManager() {
9294        return mDexManager;
9295    }
9296
9297    /**
9298     * Execute the background dexopt job immediately.
9299     */
9300    @Override
9301    public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) {
9302        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9303            return false;
9304        }
9305        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames);
9306    }
9307
9308    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9309        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9310                || p.usesStaticLibraries != null) {
9311            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9312            Set<String> collectedNames = new HashSet<>();
9313            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9314
9315            retValue.remove(p);
9316
9317            return retValue;
9318        } else {
9319            return Collections.emptyList();
9320        }
9321    }
9322
9323    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9324            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9325        if (!collectedNames.contains(p.packageName)) {
9326            collectedNames.add(p.packageName);
9327            collected.add(p);
9328
9329            if (p.usesLibraries != null) {
9330                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9331                        null, collected, collectedNames);
9332            }
9333            if (p.usesOptionalLibraries != null) {
9334                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9335                        null, collected, collectedNames);
9336            }
9337            if (p.usesStaticLibraries != null) {
9338                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9339                        p.usesStaticLibrariesVersions, collected, collectedNames);
9340            }
9341        }
9342    }
9343
9344    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions,
9345            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9346        final int libNameCount = libs.size();
9347        for (int i = 0; i < libNameCount; i++) {
9348            String libName = libs.get(i);
9349            long version = (versions != null && versions.length == libNameCount)
9350                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9351            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9352            if (libPkg != null) {
9353                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9354            }
9355        }
9356    }
9357
9358    private PackageParser.Package findSharedNonSystemLibrary(String name, long version) {
9359        synchronized (mPackages) {
9360            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9361            if (libEntry != null) {
9362                return mPackages.get(libEntry.apk);
9363            }
9364            return null;
9365        }
9366    }
9367
9368    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) {
9369        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9370        if (versionedLib == null) {
9371            return null;
9372        }
9373        return versionedLib.get(version);
9374    }
9375
9376    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9377        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9378                pkg.staticSharedLibName);
9379        if (versionedLib == null) {
9380            return null;
9381        }
9382        long previousLibVersion = -1;
9383        final int versionCount = versionedLib.size();
9384        for (int i = 0; i < versionCount; i++) {
9385            final long libVersion = versionedLib.keyAt(i);
9386            if (libVersion < pkg.staticSharedLibVersion) {
9387                previousLibVersion = Math.max(previousLibVersion, libVersion);
9388            }
9389        }
9390        if (previousLibVersion >= 0) {
9391            return versionedLib.get(previousLibVersion);
9392        }
9393        return null;
9394    }
9395
9396    public void shutdown() {
9397        mPackageUsage.writeNow(mPackages);
9398        mCompilerStats.writeNow();
9399        mDexManager.writePackageDexUsageNow();
9400    }
9401
9402    @Override
9403    public void dumpProfiles(String packageName) {
9404        PackageParser.Package pkg;
9405        synchronized (mPackages) {
9406            pkg = mPackages.get(packageName);
9407            if (pkg == null) {
9408                throw new IllegalArgumentException("Unknown package: " + packageName);
9409            }
9410        }
9411        /* Only the shell, root, or the app user should be able to dump profiles. */
9412        int callingUid = Binder.getCallingUid();
9413        if (callingUid != Process.SHELL_UID &&
9414            callingUid != Process.ROOT_UID &&
9415            callingUid != pkg.applicationInfo.uid) {
9416            throw new SecurityException("dumpProfiles");
9417        }
9418
9419        synchronized (mInstallLock) {
9420            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9421            mArtManagerService.dumpProfiles(pkg);
9422            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9423        }
9424    }
9425
9426    @Override
9427    public void forceDexOpt(String packageName) {
9428        enforceSystemOrRoot("forceDexOpt");
9429
9430        PackageParser.Package pkg;
9431        synchronized (mPackages) {
9432            pkg = mPackages.get(packageName);
9433            if (pkg == null) {
9434                throw new IllegalArgumentException("Unknown package: " + packageName);
9435            }
9436        }
9437
9438        synchronized (mInstallLock) {
9439            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9440
9441            // Whoever is calling forceDexOpt wants a compiled package.
9442            // Don't use profiles since that may cause compilation to be skipped.
9443            final int res = performDexOptInternalWithDependenciesLI(
9444                    pkg,
9445                    new DexoptOptions(packageName,
9446                            getDefaultCompilerFilter(),
9447                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9448
9449            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9450            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9451                throw new IllegalStateException("Failed to dexopt: " + res);
9452            }
9453        }
9454    }
9455
9456    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9457        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9458            Slog.w(TAG, "Unable to update from " + oldPkg.name
9459                    + " to " + newPkg.packageName
9460                    + ": old package not in system partition");
9461            return false;
9462        } else if (mPackages.get(oldPkg.name) != null) {
9463            Slog.w(TAG, "Unable to update from " + oldPkg.name
9464                    + " to " + newPkg.packageName
9465                    + ": old package still exists");
9466            return false;
9467        }
9468        return true;
9469    }
9470
9471    void removeCodePathLI(File codePath) {
9472        if (codePath.isDirectory()) {
9473            try {
9474                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9475            } catch (InstallerException e) {
9476                Slog.w(TAG, "Failed to remove code path", e);
9477            }
9478        } else {
9479            codePath.delete();
9480        }
9481    }
9482
9483    private int[] resolveUserIds(int userId) {
9484        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9485    }
9486
9487    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9488        if (pkg == null) {
9489            Slog.wtf(TAG, "Package was null!", new Throwable());
9490            return;
9491        }
9492        clearAppDataLeafLIF(pkg, userId, flags);
9493        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9494        for (int i = 0; i < childCount; i++) {
9495            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9496        }
9497
9498        clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
9499    }
9500
9501    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9502        final PackageSetting ps;
9503        synchronized (mPackages) {
9504            ps = mSettings.mPackages.get(pkg.packageName);
9505        }
9506        for (int realUserId : resolveUserIds(userId)) {
9507            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9508            try {
9509                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9510                        ceDataInode);
9511            } catch (InstallerException e) {
9512                Slog.w(TAG, String.valueOf(e));
9513            }
9514        }
9515    }
9516
9517    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9518        if (pkg == null) {
9519            Slog.wtf(TAG, "Package was null!", new Throwable());
9520            return;
9521        }
9522        destroyAppDataLeafLIF(pkg, userId, flags);
9523        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9524        for (int i = 0; i < childCount; i++) {
9525            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9526        }
9527    }
9528
9529    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9530        final PackageSetting ps;
9531        synchronized (mPackages) {
9532            ps = mSettings.mPackages.get(pkg.packageName);
9533        }
9534        for (int realUserId : resolveUserIds(userId)) {
9535            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9536            try {
9537                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9538                        ceDataInode);
9539            } catch (InstallerException e) {
9540                Slog.w(TAG, String.valueOf(e));
9541            }
9542            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9543        }
9544    }
9545
9546    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9547        if (pkg == null) {
9548            Slog.wtf(TAG, "Package was null!", new Throwable());
9549            return;
9550        }
9551        destroyAppProfilesLeafLIF(pkg);
9552        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9553        for (int i = 0; i < childCount; i++) {
9554            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9555        }
9556    }
9557
9558    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9559        try {
9560            mInstaller.destroyAppProfiles(pkg.packageName);
9561        } catch (InstallerException e) {
9562            Slog.w(TAG, String.valueOf(e));
9563        }
9564    }
9565
9566    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9567        if (pkg == null) {
9568            Slog.wtf(TAG, "Package was null!", new Throwable());
9569            return;
9570        }
9571        mArtManagerService.clearAppProfiles(pkg);
9572        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9573        for (int i = 0; i < childCount; i++) {
9574            mArtManagerService.clearAppProfiles(pkg.childPackages.get(i));
9575        }
9576    }
9577
9578    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9579            long lastUpdateTime) {
9580        // Set parent install/update time
9581        PackageSetting ps = (PackageSetting) pkg.mExtras;
9582        if (ps != null) {
9583            ps.firstInstallTime = firstInstallTime;
9584            ps.lastUpdateTime = lastUpdateTime;
9585        }
9586        // Set children install/update time
9587        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9588        for (int i = 0; i < childCount; i++) {
9589            PackageParser.Package childPkg = pkg.childPackages.get(i);
9590            ps = (PackageSetting) childPkg.mExtras;
9591            if (ps != null) {
9592                ps.firstInstallTime = firstInstallTime;
9593                ps.lastUpdateTime = lastUpdateTime;
9594            }
9595        }
9596    }
9597
9598    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9599            SharedLibraryEntry file,
9600            PackageParser.Package changingLib) {
9601        if (file.path != null) {
9602            usesLibraryFiles.add(file.path);
9603            return;
9604        }
9605        PackageParser.Package p = mPackages.get(file.apk);
9606        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9607            // If we are doing this while in the middle of updating a library apk,
9608            // then we need to make sure to use that new apk for determining the
9609            // dependencies here.  (We haven't yet finished committing the new apk
9610            // to the package manager state.)
9611            if (p == null || p.packageName.equals(changingLib.packageName)) {
9612                p = changingLib;
9613            }
9614        }
9615        if (p != null) {
9616            usesLibraryFiles.addAll(p.getAllCodePaths());
9617            if (p.usesLibraryFiles != null) {
9618                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9619            }
9620        }
9621    }
9622
9623    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9624            PackageParser.Package changingLib) throws PackageManagerException {
9625        if (pkg == null) {
9626            return;
9627        }
9628        // The collection used here must maintain the order of addition (so
9629        // that libraries are searched in the correct order) and must have no
9630        // duplicates.
9631        Set<String> usesLibraryFiles = null;
9632        if (pkg.usesLibraries != null) {
9633            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9634                    null, null, pkg.packageName, changingLib, true,
9635                    pkg.applicationInfo.targetSdkVersion, null);
9636        }
9637        if (pkg.usesStaticLibraries != null) {
9638            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9639                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9640                    pkg.packageName, changingLib, true,
9641                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9642        }
9643        if (pkg.usesOptionalLibraries != null) {
9644            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9645                    null, null, pkg.packageName, changingLib, false,
9646                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9647        }
9648        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9649            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9650        } else {
9651            pkg.usesLibraryFiles = null;
9652        }
9653    }
9654
9655    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9656            @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests,
9657            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9658            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
9659            throws PackageManagerException {
9660        final int libCount = requestedLibraries.size();
9661        for (int i = 0; i < libCount; i++) {
9662            final String libName = requestedLibraries.get(i);
9663            final long libVersion = requiredVersions != null ? requiredVersions[i]
9664                    : SharedLibraryInfo.VERSION_UNDEFINED;
9665            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9666            if (libEntry == null) {
9667                if (required) {
9668                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9669                            "Package " + packageName + " requires unavailable shared library "
9670                                    + libName + "; failing!");
9671                } else if (DEBUG_SHARED_LIBRARIES) {
9672                    Slog.i(TAG, "Package " + packageName
9673                            + " desires unavailable shared library "
9674                            + libName + "; ignoring!");
9675                }
9676            } else {
9677                if (requiredVersions != null && requiredCertDigests != null) {
9678                    if (libEntry.info.getLongVersion() != requiredVersions[i]) {
9679                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9680                            "Package " + packageName + " requires unavailable static shared"
9681                                    + " library " + libName + " version "
9682                                    + libEntry.info.getLongVersion() + "; failing!");
9683                    }
9684
9685                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9686                    if (libPkg == null) {
9687                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9688                                "Package " + packageName + " requires unavailable static shared"
9689                                        + " library; failing!");
9690                    }
9691
9692                    final String[] expectedCertDigests = requiredCertDigests[i];
9693
9694
9695                    if (expectedCertDigests.length > 1) {
9696
9697                        // For apps targeting O MR1 we require explicit enumeration of all certs.
9698                        final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
9699                                ? PackageUtils.computeSignaturesSha256Digests(
9700                                libPkg.mSigningDetails.signatures)
9701                                : PackageUtils.computeSignaturesSha256Digests(
9702                                        new Signature[]{libPkg.mSigningDetails.signatures[0]});
9703
9704                        // Take a shortcut if sizes don't match. Note that if an app doesn't
9705                        // target O we don't parse the "additional-certificate" tags similarly
9706                        // how we only consider all certs only for apps targeting O (see above).
9707                        // Therefore, the size check is safe to make.
9708                        if (expectedCertDigests.length != libCertDigests.length) {
9709                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9710                                    "Package " + packageName + " requires differently signed" +
9711                                            " static shared library; failing!");
9712                        }
9713
9714                        // Use a predictable order as signature order may vary
9715                        Arrays.sort(libCertDigests);
9716                        Arrays.sort(expectedCertDigests);
9717
9718                        final int certCount = libCertDigests.length;
9719                        for (int j = 0; j < certCount; j++) {
9720                            if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
9721                                throw new PackageManagerException(
9722                                        INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9723                                        "Package " + packageName + " requires differently signed" +
9724                                                " static shared library; failing!");
9725                            }
9726                        }
9727                    } else {
9728
9729                        // lib signing cert could have rotated beyond the one expected, check to see
9730                        // if the new one has been blessed by the old
9731                        if (!libPkg.mSigningDetails.hasSha256Certificate(
9732                                ByteStringUtils.fromHexToByteArray(expectedCertDigests[0]))) {
9733                            throw new PackageManagerException(
9734                                    INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9735                                    "Package " + packageName + " requires differently signed" +
9736                                            " static shared library; failing!");
9737                        }
9738                    }
9739                }
9740
9741                if (outUsedLibraries == null) {
9742                    // Use LinkedHashSet to preserve the order of files added to
9743                    // usesLibraryFiles while eliminating duplicates.
9744                    outUsedLibraries = new LinkedHashSet<>();
9745                }
9746                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9747            }
9748        }
9749        return outUsedLibraries;
9750    }
9751
9752    private static boolean hasString(List<String> list, List<String> which) {
9753        if (list == null) {
9754            return false;
9755        }
9756        for (int i=list.size()-1; i>=0; i--) {
9757            for (int j=which.size()-1; j>=0; j--) {
9758                if (which.get(j).equals(list.get(i))) {
9759                    return true;
9760                }
9761            }
9762        }
9763        return false;
9764    }
9765
9766    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9767            PackageParser.Package changingPkg) {
9768        ArrayList<PackageParser.Package> res = null;
9769        for (PackageParser.Package pkg : mPackages.values()) {
9770            if (changingPkg != null
9771                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9772                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9773                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9774                            changingPkg.staticSharedLibName)) {
9775                return null;
9776            }
9777            if (res == null) {
9778                res = new ArrayList<>();
9779            }
9780            res.add(pkg);
9781            try {
9782                updateSharedLibrariesLPr(pkg, changingPkg);
9783            } catch (PackageManagerException e) {
9784                // If a system app update or an app and a required lib missing we
9785                // delete the package and for updated system apps keep the data as
9786                // it is better for the user to reinstall than to be in an limbo
9787                // state. Also libs disappearing under an app should never happen
9788                // - just in case.
9789                if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) {
9790                    final int flags = pkg.isUpdatedSystemApp()
9791                            ? PackageManager.DELETE_KEEP_DATA : 0;
9792                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9793                            flags , null, true, null);
9794                }
9795                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9796            }
9797        }
9798        return res;
9799    }
9800
9801    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9802            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9803            @Nullable UserHandle user) throws PackageManagerException {
9804        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9805        // If the package has children and this is the first dive in the function
9806        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9807        // whether all packages (parent and children) would be successfully scanned
9808        // before the actual scan since scanning mutates internal state and we want
9809        // to atomically install the package and its children.
9810        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9811            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9812                scanFlags |= SCAN_CHECK_ONLY;
9813            }
9814        } else {
9815            scanFlags &= ~SCAN_CHECK_ONLY;
9816        }
9817
9818        final PackageParser.Package scannedPkg;
9819        try {
9820            // Scan the parent
9821            scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user);
9822            // Scan the children
9823            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9824            for (int i = 0; i < childCount; i++) {
9825                PackageParser.Package childPkg = pkg.childPackages.get(i);
9826                scanPackageNewLI(childPkg, parseFlags,
9827                        scanFlags, currentTime, user);
9828            }
9829        } finally {
9830            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9831        }
9832
9833        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9834            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
9835        }
9836
9837        return scannedPkg;
9838    }
9839
9840    /** The result of a package scan. */
9841    private static class ScanResult {
9842        /** Whether or not the package scan was successful */
9843        public final boolean success;
9844        /**
9845         * The final package settings. This may be the same object passed in
9846         * the {@link ScanRequest}, but, with modified values.
9847         */
9848        @Nullable public final PackageSetting pkgSetting;
9849        /** ABI code paths that have changed in the package scan */
9850        @Nullable public final List<String> changedAbiCodePath;
9851        public ScanResult(
9852                boolean success,
9853                @Nullable PackageSetting pkgSetting,
9854                @Nullable List<String> changedAbiCodePath) {
9855            this.success = success;
9856            this.pkgSetting = pkgSetting;
9857            this.changedAbiCodePath = changedAbiCodePath;
9858        }
9859    }
9860
9861    /** A package to be scanned */
9862    private static class ScanRequest {
9863        /** The parsed package */
9864        @NonNull public final PackageParser.Package pkg;
9865        /** Shared user settings, if the package has a shared user */
9866        @Nullable public final SharedUserSetting sharedUserSetting;
9867        /**
9868         * Package settings of the currently installed version.
9869         * <p><em>IMPORTANT:</em> The contents of this object may be modified
9870         * during scan.
9871         */
9872        @Nullable public final PackageSetting pkgSetting;
9873        /** A copy of the settings for the currently installed version */
9874        @Nullable public final PackageSetting oldPkgSetting;
9875        /** Package settings for the disabled version on the /system partition */
9876        @Nullable public final PackageSetting disabledPkgSetting;
9877        /** Package settings for the installed version under its original package name */
9878        @Nullable public final PackageSetting originalPkgSetting;
9879        /** The real package name of a renamed application */
9880        @Nullable public final String realPkgName;
9881        public final @ParseFlags int parseFlags;
9882        public final @ScanFlags int scanFlags;
9883        /** The user for which the package is being scanned */
9884        @Nullable public final UserHandle user;
9885        /** Whether or not the platform package is being scanned */
9886        public final boolean isPlatformPackage;
9887        public ScanRequest(
9888                @NonNull PackageParser.Package pkg,
9889                @Nullable SharedUserSetting sharedUserSetting,
9890                @Nullable PackageSetting pkgSetting,
9891                @Nullable PackageSetting disabledPkgSetting,
9892                @Nullable PackageSetting originalPkgSetting,
9893                @Nullable String realPkgName,
9894                @ParseFlags int parseFlags,
9895                @ScanFlags int scanFlags,
9896                boolean isPlatformPackage,
9897                @Nullable UserHandle user) {
9898            this.pkg = pkg;
9899            this.pkgSetting = pkgSetting;
9900            this.sharedUserSetting = sharedUserSetting;
9901            this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting);
9902            this.disabledPkgSetting = disabledPkgSetting;
9903            this.originalPkgSetting = originalPkgSetting;
9904            this.realPkgName = realPkgName;
9905            this.parseFlags = parseFlags;
9906            this.scanFlags = scanFlags;
9907            this.isPlatformPackage = isPlatformPackage;
9908            this.user = user;
9909        }
9910    }
9911
9912    /**
9913     * Returns the actual scan flags depending upon the state of the other settings.
9914     * <p>Updated system applications will not have the following flags set
9915     * by default and need to be adjusted after the fact:
9916     * <ul>
9917     * <li>{@link #SCAN_AS_SYSTEM}</li>
9918     * <li>{@link #SCAN_AS_PRIVILEGED}</li>
9919     * <li>{@link #SCAN_AS_OEM}</li>
9920     * <li>{@link #SCAN_AS_VENDOR}</li>
9921     * <li>{@link #SCAN_AS_PRODUCT}</li>
9922     * <li>{@link #SCAN_AS_INSTANT_APP}</li>
9923     * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li>
9924     * </ul>
9925     */
9926    private @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags,
9927            PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user,
9928            PackageParser.Package pkg) {
9929        if (disabledPkgSetting != null) {
9930            // updated system application, must at least have SCAN_AS_SYSTEM
9931            scanFlags |= SCAN_AS_SYSTEM;
9932            if ((disabledPkgSetting.pkgPrivateFlags
9933                    & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9934                scanFlags |= SCAN_AS_PRIVILEGED;
9935            }
9936            if ((disabledPkgSetting.pkgPrivateFlags
9937                    & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
9938                scanFlags |= SCAN_AS_OEM;
9939            }
9940            if ((disabledPkgSetting.pkgPrivateFlags
9941                    & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) {
9942                scanFlags |= SCAN_AS_VENDOR;
9943            }
9944            if ((disabledPkgSetting.pkgPrivateFlags
9945                    & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0) {
9946                scanFlags |= SCAN_AS_PRODUCT;
9947            }
9948        }
9949        if (pkgSetting != null) {
9950            final int userId = ((user == null) ? 0 : user.getIdentifier());
9951            if (pkgSetting.getInstantApp(userId)) {
9952                scanFlags |= SCAN_AS_INSTANT_APP;
9953            }
9954            if (pkgSetting.getVirtulalPreload(userId)) {
9955                scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9956            }
9957        }
9958
9959        // Scan as privileged apps that share a user with a priv-app.
9960        if (((scanFlags & SCAN_AS_PRIVILEGED) == 0) && !pkg.isPrivileged()
9961                && (pkg.mSharedUserId != null)) {
9962            SharedUserSetting sharedUserSetting = null;
9963            try {
9964                sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
9965            } catch (PackageManagerException ignore) {}
9966            if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
9967                // Exempt SharedUsers signed with the platform key.
9968                // TODO(b/72378145) Fix this exemption. Force signature apps
9969                // to whitelist their privileged permissions just like other
9970                // priv-apps.
9971                synchronized (mPackages) {
9972                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
9973                    if ((compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures,
9974                                pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) {
9975                        scanFlags |= SCAN_AS_PRIVILEGED;
9976                    }
9977                }
9978            }
9979        }
9980
9981        return scanFlags;
9982    }
9983
9984    // TODO: scanPackageNewLI() and scanPackageOnly() should be merged. But, first, commiting
9985    // the results / removing app data needs to be moved up a level to the callers of this
9986    // method. Also, we need to solve the problem of potentially creating a new shared user
9987    // setting. That can probably be done later and patch things up after the fact.
9988    @GuardedBy("mInstallLock")
9989    private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg,
9990            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9991            @Nullable UserHandle user) throws PackageManagerException {
9992
9993        final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9994        final String realPkgName = getRealPackageName(pkg, renamedPkgName);
9995        if (realPkgName != null) {
9996            ensurePackageRenamed(pkg, renamedPkgName);
9997        }
9998        final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
9999        final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10000        final PackageSetting disabledPkgSetting =
10001                mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10002
10003        if (mTransferedPackages.contains(pkg.packageName)) {
10004            Slog.w(TAG, "Package " + pkg.packageName
10005                    + " was transferred to another, but its .apk remains");
10006        }
10007
10008        scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user, pkg);
10009        synchronized (mPackages) {
10010            applyPolicy(pkg, parseFlags, scanFlags);
10011            assertPackageIsValid(pkg, parseFlags, scanFlags);
10012
10013            SharedUserSetting sharedUserSetting = null;
10014            if (pkg.mSharedUserId != null) {
10015                // SIDE EFFECTS; may potentially allocate a new shared user
10016                sharedUserSetting = mSettings.getSharedUserLPw(
10017                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10018                if (DEBUG_PACKAGE_SCANNING) {
10019                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10020                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
10021                                + " (uid=" + sharedUserSetting.userId + "):"
10022                                + " packages=" + sharedUserSetting.packages);
10023                }
10024            }
10025
10026            boolean scanSucceeded = false;
10027            try {
10028                final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, pkgSetting,
10029                        disabledPkgSetting, originalPkgSetting, realPkgName, parseFlags, scanFlags,
10030                        (pkg == mPlatformPackage), user);
10031                final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime);
10032                if (result.success) {
10033                    commitScanResultsLocked(request, result);
10034                }
10035                scanSucceeded = true;
10036            } finally {
10037                  if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10038                      // DELETE_DATA_ON_FAILURES is only used by frozen paths
10039                      destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10040                              StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10041                      destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10042                  }
10043            }
10044        }
10045        return pkg;
10046    }
10047
10048    /**
10049     * Commits the package scan and modifies system state.
10050     * <p><em>WARNING:</em> The method may throw an excpetion in the middle
10051     * of committing the package, leaving the system in an inconsistent state.
10052     * This needs to be fixed so, once we get to this point, no errors are
10053     * possible and the system is not left in an inconsistent state.
10054     */
10055    @GuardedBy("mPackages")
10056    private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result)
10057            throws PackageManagerException {
10058        final PackageParser.Package pkg = request.pkg;
10059        final @ParseFlags int parseFlags = request.parseFlags;
10060        final @ScanFlags int scanFlags = request.scanFlags;
10061        final PackageSetting oldPkgSetting = request.oldPkgSetting;
10062        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10063        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10064        final UserHandle user = request.user;
10065        final String realPkgName = request.realPkgName;
10066        final PackageSetting pkgSetting = result.pkgSetting;
10067        final List<String> changedAbiCodePath = result.changedAbiCodePath;
10068        final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting);
10069
10070        if (newPkgSettingCreated) {
10071            if (originalPkgSetting != null) {
10072                mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name);
10073            }
10074            // THROWS: when we can't allocate a user id. add call to check if there's
10075            // enough space to ensure we won't throw; otherwise, don't modify state
10076            mSettings.addUserToSettingLPw(pkgSetting);
10077
10078            if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) {
10079                mTransferedPackages.add(originalPkgSetting.name);
10080            }
10081        }
10082        // TODO(toddke): Consider a method specifically for modifying the Package object
10083        // post scan; or, moving this stuff out of the Package object since it has nothing
10084        // to do with the package on disk.
10085        // We need to have this here because addUserToSettingLPw() is sometimes responsible
10086        // for creating the application ID. If we did this earlier, we would be saving the
10087        // correct ID.
10088        pkg.applicationInfo.uid = pkgSetting.appId;
10089
10090        mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10091
10092        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) {
10093            mTransferedPackages.add(pkg.packageName);
10094        }
10095
10096        // THROWS: when requested libraries that can't be found. it only changes
10097        // the state of the passed in pkg object, so, move to the top of the method
10098        // and allow it to abort
10099        if ((scanFlags & SCAN_BOOTING) == 0
10100                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10101            // Check all shared libraries and map to their actual file path.
10102            // We only do this here for apps not on a system dir, because those
10103            // are the only ones that can fail an install due to this.  We
10104            // will take care of the system apps by updating all of their
10105            // library paths after the scan is done. Also during the initial
10106            // scan don't update any libs as we do this wholesale after all
10107            // apps are scanned to avoid dependency based scanning.
10108            updateSharedLibrariesLPr(pkg, null);
10109        }
10110
10111        // All versions of a static shared library are referenced with the same
10112        // package name. Internally, we use a synthetic package name to allow
10113        // multiple versions of the same shared library to be installed. So,
10114        // we need to generate the synthetic package name of the latest shared
10115        // library in order to compare signatures.
10116        PackageSetting signatureCheckPs = pkgSetting;
10117        if (pkg.applicationInfo.isStaticSharedLibrary()) {
10118            SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10119            if (libraryEntry != null) {
10120                signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10121            }
10122        }
10123
10124        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10125        if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
10126            if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
10127                // We just determined the app is signed correctly, so bring
10128                // over the latest parsed certs.
10129                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10130            } else {
10131                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10132                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10133                            "Package " + pkg.packageName + " upgrade keys do not match the "
10134                                    + "previously installed version");
10135                } else {
10136                    pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10137                    String msg = "System package " + pkg.packageName
10138                            + " signature changed; retaining data.";
10139                    reportSettingsProblem(Log.WARN, msg);
10140                }
10141            }
10142        } else {
10143            try {
10144                final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
10145                final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
10146                final boolean compatMatch = verifySignatures(signatureCheckPs, disabledPkgSetting,
10147                        pkg.mSigningDetails, compareCompat, compareRecover);
10148                // The new KeySets will be re-added later in the scanning process.
10149                if (compatMatch) {
10150                    synchronized (mPackages) {
10151                        ksms.removeAppKeySetDataLPw(pkg.packageName);
10152                    }
10153                }
10154                // We just determined the app is signed correctly, so bring
10155                // over the latest parsed certs.
10156                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10157
10158
10159                // if this is is a sharedUser, check to see if the new package is signed by a newer
10160                // signing certificate than the existing one, and if so, copy over the new details
10161                if (signatureCheckPs.sharedUser != null
10162                        && pkg.mSigningDetails.hasAncestor(
10163                                signatureCheckPs.sharedUser.signatures.mSigningDetails)) {
10164                    signatureCheckPs.sharedUser.signatures.mSigningDetails = pkg.mSigningDetails;
10165                }
10166            } catch (PackageManagerException e) {
10167                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10168                    throw e;
10169                }
10170                // The signature has changed, but this package is in the system
10171                // image...  let's recover!
10172                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10173                // However...  if this package is part of a shared user, but it
10174                // doesn't match the signature of the shared user, let's fail.
10175                // What this means is that you can't change the signatures
10176                // associated with an overall shared user, which doesn't seem all
10177                // that unreasonable.
10178                if (signatureCheckPs.sharedUser != null) {
10179                    if (compareSignatures(
10180                            signatureCheckPs.sharedUser.signatures.mSigningDetails.signatures,
10181                            pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH) {
10182                        throw new PackageManagerException(
10183                                INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10184                                "Signature mismatch for shared user: "
10185                                        + pkgSetting.sharedUser);
10186                    }
10187                }
10188                // File a report about this.
10189                String msg = "System package " + pkg.packageName
10190                        + " signature changed; retaining data.";
10191                reportSettingsProblem(Log.WARN, msg);
10192            } catch (IllegalArgumentException e) {
10193
10194                // should never happen: certs matched when checking, but not when comparing
10195                // old to new for sharedUser
10196                throw new PackageManagerException(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10197                        "Signing certificates comparison made on incomparable signing details"
10198                        + " but somehow passed verifySignatures!");
10199            }
10200        }
10201
10202        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10203            // This package wants to adopt ownership of permissions from
10204            // another package.
10205            for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10206                final String origName = pkg.mAdoptPermissions.get(i);
10207                final PackageSetting orig = mSettings.getPackageLPr(origName);
10208                if (orig != null) {
10209                    if (verifyPackageUpdateLPr(orig, pkg)) {
10210                        Slog.i(TAG, "Adopting permissions from " + origName + " to "
10211                                + pkg.packageName);
10212                        mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
10213                    }
10214                }
10215            }
10216        }
10217
10218        if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
10219            for (int i = changedAbiCodePath.size() - 1; i <= 0; --i) {
10220                final String codePathString = changedAbiCodePath.get(i);
10221                try {
10222                    mInstaller.rmdex(codePathString,
10223                            getDexCodeInstructionSet(getPreferredInstructionSet()));
10224                } catch (InstallerException ignored) {
10225                }
10226            }
10227        }
10228
10229        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10230            if (oldPkgSetting != null) {
10231                synchronized (mPackages) {
10232                    mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting);
10233                }
10234            }
10235        } else {
10236            final int userId = user == null ? 0 : user.getIdentifier();
10237            // Modify state for the given package setting
10238            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10239                    (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10240            if (pkgSetting.getInstantApp(userId)) {
10241                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10242            }
10243        }
10244    }
10245
10246    /**
10247     * Returns the "real" name of the package.
10248     * <p>This may differ from the package's actual name if the application has already
10249     * been installed under one of this package's original names.
10250     */
10251    private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg,
10252            @Nullable String renamedPkgName) {
10253        if (isPackageRenamed(pkg, renamedPkgName)) {
10254            return pkg.mRealPackage;
10255        }
10256        return null;
10257    }
10258
10259    /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */
10260    private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg,
10261            @Nullable String renamedPkgName) {
10262        return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName);
10263    }
10264
10265    /**
10266     * Returns the original package setting.
10267     * <p>A package can migrate its name during an update. In this scenario, a package
10268     * designates a set of names that it considers as one of its original names.
10269     * <p>An original package must be signed identically and it must have the same
10270     * shared user [if any].
10271     */
10272    @GuardedBy("mPackages")
10273    private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg,
10274            @Nullable String renamedPkgName) {
10275        if (!isPackageRenamed(pkg, renamedPkgName)) {
10276            return null;
10277        }
10278        for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) {
10279            final PackageSetting originalPs =
10280                    mSettings.getPackageLPr(pkg.mOriginalPackages.get(i));
10281            if (originalPs != null) {
10282                // the package is already installed under its original name...
10283                // but, should we use it?
10284                if (!verifyPackageUpdateLPr(originalPs, pkg)) {
10285                    // the new package is incompatible with the original
10286                    continue;
10287                } else if (originalPs.sharedUser != null) {
10288                    if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) {
10289                        // the shared user id is incompatible with the original
10290                        Slog.w(TAG, "Unable to migrate data from " + originalPs.name
10291                                + " to " + pkg.packageName + ": old uid "
10292                                + originalPs.sharedUser.name
10293                                + " differs from " + pkg.mSharedUserId);
10294                        continue;
10295                    }
10296                    // TODO: Add case when shared user id is added [b/28144775]
10297                } else {
10298                    if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10299                            + pkg.packageName + " to old name " + originalPs.name);
10300                }
10301                return originalPs;
10302            }
10303        }
10304        return null;
10305    }
10306
10307    /**
10308     * Renames the package if it was installed under a different name.
10309     * <p>When we've already installed the package under an original name, update
10310     * the new package so we can continue to have the old name.
10311     */
10312    private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg,
10313            @NonNull String renamedPackageName) {
10314        if (pkg.mOriginalPackages == null
10315                || !pkg.mOriginalPackages.contains(renamedPackageName)
10316                || pkg.packageName.equals(renamedPackageName)) {
10317            return;
10318        }
10319        pkg.setPackageName(renamedPackageName);
10320    }
10321
10322    /**
10323     * Just scans the package without any side effects.
10324     * <p>Not entirely true at the moment. There is still one side effect -- this
10325     * method potentially modifies a live {@link PackageSetting} object representing
10326     * the package being scanned. This will be resolved in the future.
10327     *
10328     * @param request Information about the package to be scanned
10329     * @param isUnderFactoryTest Whether or not the device is under factory test
10330     * @param currentTime The current time, in millis
10331     * @return The results of the scan
10332     */
10333    @GuardedBy("mInstallLock")
10334    private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request,
10335            boolean isUnderFactoryTest, long currentTime)
10336                    throws PackageManagerException {
10337        final PackageParser.Package pkg = request.pkg;
10338        PackageSetting pkgSetting = request.pkgSetting;
10339        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10340        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10341        final @ParseFlags int parseFlags = request.parseFlags;
10342        final @ScanFlags int scanFlags = request.scanFlags;
10343        final String realPkgName = request.realPkgName;
10344        final SharedUserSetting sharedUserSetting = request.sharedUserSetting;
10345        final UserHandle user = request.user;
10346        final boolean isPlatformPackage = request.isPlatformPackage;
10347
10348        List<String> changedAbiCodePath = null;
10349
10350        if (DEBUG_PACKAGE_SCANNING) {
10351            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10352                Log.d(TAG, "Scanning package " + pkg.packageName);
10353        }
10354
10355        if (Build.IS_DEBUGGABLE &&
10356                pkg.isPrivileged() &&
10357                !SystemProperties.getBoolean(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB, true)) {
10358            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10359        }
10360
10361        // Initialize package source and resource directories
10362        final File scanFile = new File(pkg.codePath);
10363        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10364        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10365
10366        // We keep references to the derived CPU Abis from settings in oder to reuse
10367        // them in the case where we're not upgrading or booting for the first time.
10368        String primaryCpuAbiFromSettings = null;
10369        String secondaryCpuAbiFromSettings = null;
10370        boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0;
10371
10372        if (!needToDeriveAbi) {
10373            if (pkgSetting != null) {
10374                primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString;
10375                secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString;
10376            } else {
10377                // Re-scanning a system package after uninstalling updates; need to derive ABI
10378                needToDeriveAbi = true;
10379            }
10380        }
10381
10382        if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) {
10383            PackageManagerService.reportSettingsProblem(Log.WARN,
10384                    "Package " + pkg.packageName + " shared user changed from "
10385                            + (pkgSetting.sharedUser != null
10386                            ? pkgSetting.sharedUser.name : "<nothing>")
10387                            + " to "
10388                            + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>")
10389                            + "; replacing with new");
10390            pkgSetting = null;
10391        }
10392
10393        String[] usesStaticLibraries = null;
10394        if (pkg.usesStaticLibraries != null) {
10395            usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10396            pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10397        }
10398        final boolean createNewPackage = (pkgSetting == null);
10399        if (createNewPackage) {
10400            final String parentPackageName = (pkg.parentPackage != null)
10401                    ? pkg.parentPackage.packageName : null;
10402            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10403            final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10404            // REMOVE SharedUserSetting from method; update in a separate call
10405            pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting,
10406                    disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile,
10407                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
10408                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10409                    pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10410                    user, true /*allowInstall*/, instantApp, virtualPreload,
10411                    parentPackageName, pkg.getChildPackageNames(),
10412                    UserManagerService.getInstance(), usesStaticLibraries,
10413                    pkg.usesStaticLibrariesVersions);
10414        } else {
10415            // REMOVE SharedUserSetting from method; update in a separate call.
10416            //
10417            // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10418            // secondaryCpuAbi are not known at this point so we always update them
10419            // to null here, only to reset them at a later point.
10420            Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting,
10421                    destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir,
10422                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10423                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10424                    pkg.getChildPackageNames(), UserManagerService.getInstance(),
10425                    usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10426        }
10427        if (createNewPackage && originalPkgSetting != null) {
10428            // This is the initial transition from the original package, so,
10429            // fix up the new package's name now. We must do this after looking
10430            // up the package under its new name, so getPackageLP takes care of
10431            // fiddling things correctly.
10432            pkg.setPackageName(originalPkgSetting.name);
10433
10434            // File a report about this.
10435            String msg = "New package " + pkgSetting.realName
10436                    + " renamed to replace old package " + pkgSetting.name;
10437            reportSettingsProblem(Log.WARN, msg);
10438        }
10439
10440        if (disabledPkgSetting != null) {
10441            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10442        }
10443
10444        // Apps which share a sharedUserId must be placed in the same selinux domain. If this
10445        // package is the first app installed as this shared user, set seInfoTargetSdkVersion to its
10446        // targetSdkVersion. These are later adjusted in PackageManagerService's constructor to be
10447        // the lowest targetSdkVersion of all apps within the shared user, which corresponds to the
10448        // least restrictive selinux domain.
10449        // NOTE: As new packages are installed / updated, the shared user's seinfoTargetSdkVersion
10450        // will NOT be modified until next boot, even if a lower targetSdkVersion is used. This
10451        // ensures that all packages continue to run in the same selinux domain.
10452        final int targetSdkVersion =
10453            ((sharedUserSetting != null) && (sharedUserSetting.packages.size() != 0)) ?
10454            sharedUserSetting.seInfoTargetSdkVersion : pkg.applicationInfo.targetSdkVersion;
10455        // TODO(b/71593002): isPrivileged for sharedUser and appInfo should never be out of sync.
10456        // They currently can be if the sharedUser apps are signed with the platform key.
10457        final boolean isPrivileged = (sharedUserSetting != null) ?
10458            sharedUserSetting.isPrivileged() | pkg.isPrivileged() : pkg.isPrivileged();
10459
10460        pkg.applicationInfo.seInfo = SELinuxMMAC.getSeInfo(pkg, isPrivileged,
10461                pkg.applicationInfo.targetSandboxVersion, targetSdkVersion);
10462
10463        pkg.mExtras = pkgSetting;
10464        pkg.applicationInfo.processName = fixProcessName(
10465                pkg.applicationInfo.packageName,
10466                pkg.applicationInfo.processName);
10467
10468        if (!isPlatformPackage) {
10469            // Get all of our default paths setup
10470            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10471        }
10472
10473        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10474
10475        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10476            if (needToDeriveAbi) {
10477                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10478                final boolean extractNativeLibs = !pkg.isLibrary();
10479                derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs);
10480                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10481
10482                // Some system apps still use directory structure for native libraries
10483                // in which case we might end up not detecting abi solely based on apk
10484                // structure. Try to detect abi based on directory structure.
10485                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10486                        pkg.applicationInfo.primaryCpuAbi == null) {
10487                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10488                    setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10489                }
10490            } else {
10491                // This is not a first boot or an upgrade, don't bother deriving the
10492                // ABI during the scan. Instead, trust the value that was stored in the
10493                // package setting.
10494                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10495                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10496
10497                setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10498
10499                if (DEBUG_ABI_SELECTION) {
10500                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10501                            pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10502                            pkg.applicationInfo.secondaryCpuAbi);
10503                }
10504            }
10505        } else {
10506            if ((scanFlags & SCAN_MOVE) != 0) {
10507                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10508                // but we already have this packages package info in the PackageSetting. We just
10509                // use that and derive the native library path based on the new codepath.
10510                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10511                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10512            }
10513
10514            // Set native library paths again. For moves, the path will be updated based on the
10515            // ABIs we've determined above. For non-moves, the path will be updated based on the
10516            // ABIs we determined during compilation, but the path will depend on the final
10517            // package path (after the rename away from the stage path).
10518            setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10519        }
10520
10521        // This is a special case for the "system" package, where the ABI is
10522        // dictated by the zygote configuration (and init.rc). We should keep track
10523        // of this ABI so that we can deal with "normal" applications that run under
10524        // the same UID correctly.
10525        if (isPlatformPackage) {
10526            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10527                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10528        }
10529
10530        // If there's a mismatch between the abi-override in the package setting
10531        // and the abiOverride specified for the install. Warn about this because we
10532        // would've already compiled the app without taking the package setting into
10533        // account.
10534        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10535            if (cpuAbiOverride == null && pkg.packageName != null) {
10536                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10537                        " for package " + pkg.packageName);
10538            }
10539        }
10540
10541        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10542        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10543        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10544
10545        // Copy the derived override back to the parsed package, so that we can
10546        // update the package settings accordingly.
10547        pkg.cpuAbiOverride = cpuAbiOverride;
10548
10549        if (DEBUG_ABI_SELECTION) {
10550            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName
10551                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10552                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10553        }
10554
10555        // Push the derived path down into PackageSettings so we know what to
10556        // clean up at uninstall time.
10557        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10558
10559        if (DEBUG_ABI_SELECTION) {
10560            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10561                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10562                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10563        }
10564
10565        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10566            // We don't do this here during boot because we can do it all
10567            // at once after scanning all existing packages.
10568            //
10569            // We also do this *before* we perform dexopt on this package, so that
10570            // we can avoid redundant dexopts, and also to make sure we've got the
10571            // code and package path correct.
10572            changedAbiCodePath =
10573                    adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10574        }
10575
10576        if (isUnderFactoryTest && pkg.requestedPermissions.contains(
10577                android.Manifest.permission.FACTORY_TEST)) {
10578            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10579        }
10580
10581        if (isSystemApp(pkg)) {
10582            pkgSetting.isOrphaned = true;
10583        }
10584
10585        // Take care of first install / last update times.
10586        final long scanFileTime = getLastModifiedTime(pkg);
10587        if (currentTime != 0) {
10588            if (pkgSetting.firstInstallTime == 0) {
10589                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10590            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10591                pkgSetting.lastUpdateTime = currentTime;
10592            }
10593        } else if (pkgSetting.firstInstallTime == 0) {
10594            // We need *something*.  Take time time stamp of the file.
10595            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10596        } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10597            if (scanFileTime != pkgSetting.timeStamp) {
10598                // A package on the system image has changed; consider this
10599                // to be an update.
10600                pkgSetting.lastUpdateTime = scanFileTime;
10601            }
10602        }
10603        pkgSetting.setTimeStamp(scanFileTime);
10604
10605        pkgSetting.pkg = pkg;
10606        pkgSetting.pkgFlags = pkg.applicationInfo.flags;
10607        if (pkg.getLongVersionCode() != pkgSetting.versionCode) {
10608            pkgSetting.versionCode = pkg.getLongVersionCode();
10609        }
10610        // Update volume if needed
10611        final String volumeUuid = pkg.applicationInfo.volumeUuid;
10612        if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) {
10613            Slog.i(PackageManagerService.TAG,
10614                    "Update" + (pkgSetting.isSystem() ? " system" : "")
10615                    + " package " + pkg.packageName
10616                    + " volume from " + pkgSetting.volumeUuid
10617                    + " to " + volumeUuid);
10618            pkgSetting.volumeUuid = volumeUuid;
10619        }
10620
10621        return new ScanResult(true, pkgSetting, changedAbiCodePath);
10622    }
10623
10624    /**
10625     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10626     */
10627    private static boolean apkHasCode(String fileName) {
10628        StrictJarFile jarFile = null;
10629        try {
10630            jarFile = new StrictJarFile(fileName,
10631                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10632            return jarFile.findEntry("classes.dex") != null;
10633        } catch (IOException ignore) {
10634        } finally {
10635            try {
10636                if (jarFile != null) {
10637                    jarFile.close();
10638                }
10639            } catch (IOException ignore) {}
10640        }
10641        return false;
10642    }
10643
10644    /**
10645     * Enforces code policy for the package. This ensures that if an APK has
10646     * declared hasCode="true" in its manifest that the APK actually contains
10647     * code.
10648     *
10649     * @throws PackageManagerException If bytecode could not be found when it should exist
10650     */
10651    private static void assertCodePolicy(PackageParser.Package pkg)
10652            throws PackageManagerException {
10653        final boolean shouldHaveCode =
10654                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10655        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10656            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10657                    "Package " + pkg.baseCodePath + " code is missing");
10658        }
10659
10660        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10661            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10662                final boolean splitShouldHaveCode =
10663                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10664                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10665                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10666                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10667                }
10668            }
10669        }
10670    }
10671
10672    /**
10673     * Applies policy to the parsed package based upon the given policy flags.
10674     * Ensures the package is in a good state.
10675     * <p>
10676     * Implementation detail: This method must NOT have any side effect. It would
10677     * ideally be static, but, it requires locks to read system state.
10678     */
10679    private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10680            final @ScanFlags int scanFlags) {
10681        if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10682            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10683            if (pkg.applicationInfo.isDirectBootAware()) {
10684                // we're direct boot aware; set for all components
10685                for (PackageParser.Service s : pkg.services) {
10686                    s.info.encryptionAware = s.info.directBootAware = true;
10687                }
10688                for (PackageParser.Provider p : pkg.providers) {
10689                    p.info.encryptionAware = p.info.directBootAware = true;
10690                }
10691                for (PackageParser.Activity a : pkg.activities) {
10692                    a.info.encryptionAware = a.info.directBootAware = true;
10693                }
10694                for (PackageParser.Activity r : pkg.receivers) {
10695                    r.info.encryptionAware = r.info.directBootAware = true;
10696                }
10697            }
10698            if (compressedFileExists(pkg.codePath)) {
10699                pkg.isStub = true;
10700            }
10701        } else {
10702            // non system apps can't be flagged as core
10703            pkg.coreApp = false;
10704            // clear flags not applicable to regular apps
10705            pkg.applicationInfo.flags &=
10706                    ~ApplicationInfo.FLAG_PERSISTENT;
10707            pkg.applicationInfo.privateFlags &=
10708                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10709            pkg.applicationInfo.privateFlags &=
10710                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10711            // cap permission priorities
10712            if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) {
10713                for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) {
10714                    pkg.permissionGroups.get(i).info.priority = 0;
10715                }
10716            }
10717        }
10718        if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10719            // clear protected broadcasts
10720            pkg.protectedBroadcasts = null;
10721            // ignore export request for single user receivers
10722            if (pkg.receivers != null) {
10723                for (int i = pkg.receivers.size() - 1; i >= 0; --i) {
10724                    final PackageParser.Activity receiver = pkg.receivers.get(i);
10725                    if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) {
10726                        receiver.info.exported = false;
10727                    }
10728                }
10729            }
10730            // ignore export request for single user services
10731            if (pkg.services != null) {
10732                for (int i = pkg.services.size() - 1; i >= 0; --i) {
10733                    final PackageParser.Service service = pkg.services.get(i);
10734                    if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
10735                        service.info.exported = false;
10736                    }
10737                }
10738            }
10739            // ignore export request for single user providers
10740            if (pkg.providers != null) {
10741                for (int i = pkg.providers.size() - 1; i >= 0; --i) {
10742                    final PackageParser.Provider provider = pkg.providers.get(i);
10743                    if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) {
10744                        provider.info.exported = false;
10745                    }
10746                }
10747            }
10748        }
10749
10750        if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) {
10751            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10752        }
10753
10754        if ((scanFlags & SCAN_AS_OEM) != 0) {
10755            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10756        }
10757
10758        if ((scanFlags & SCAN_AS_VENDOR) != 0) {
10759            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR;
10760        }
10761
10762        if ((scanFlags & SCAN_AS_PRODUCT) != 0) {
10763            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRODUCT;
10764        }
10765
10766        if (!isSystemApp(pkg)) {
10767            // Only system apps can use these features.
10768            pkg.mOriginalPackages = null;
10769            pkg.mRealPackage = null;
10770            pkg.mAdoptPermissions = null;
10771        }
10772    }
10773
10774    private static @NonNull <T> T assertNotNull(@Nullable T object, String message)
10775            throws PackageManagerException {
10776        if (object == null) {
10777            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, message);
10778        }
10779        return object;
10780    }
10781
10782    /**
10783     * Asserts the parsed package is valid according to the given policy. If the
10784     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10785     * <p>
10786     * Implementation detail: This method must NOT have any side effects. It would
10787     * ideally be static, but, it requires locks to read system state.
10788     *
10789     * @throws PackageManagerException If the package fails any of the validation checks
10790     */
10791    private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10792            final @ScanFlags int scanFlags)
10793                    throws PackageManagerException {
10794        if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10795            assertCodePolicy(pkg);
10796        }
10797
10798        if (pkg.applicationInfo.getCodePath() == null ||
10799                pkg.applicationInfo.getResourcePath() == null) {
10800            // Bail out. The resource and code paths haven't been set.
10801            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10802                    "Code and resource paths haven't been set correctly");
10803        }
10804
10805        // Make sure we're not adding any bogus keyset info
10806        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10807        ksms.assertScannedPackageValid(pkg);
10808
10809        synchronized (mPackages) {
10810            // The special "android" package can only be defined once
10811            if (pkg.packageName.equals("android")) {
10812                if (mAndroidApplication != null) {
10813                    Slog.w(TAG, "*************************************************");
10814                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10815                    Slog.w(TAG, " codePath=" + pkg.codePath);
10816                    Slog.w(TAG, "*************************************************");
10817                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10818                            "Core android package being redefined.  Skipping.");
10819                }
10820            }
10821
10822            // A package name must be unique; don't allow duplicates
10823            if (mPackages.containsKey(pkg.packageName)) {
10824                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10825                        "Application package " + pkg.packageName
10826                        + " already installed.  Skipping duplicate.");
10827            }
10828
10829            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10830                // Static libs have a synthetic package name containing the version
10831                // but we still want the base name to be unique.
10832                if (mPackages.containsKey(pkg.manifestPackageName)) {
10833                    throw new PackageManagerException(
10834                            "Duplicate static shared lib provider package");
10835                }
10836
10837                // Static shared libraries should have at least O target SDK
10838                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10839                    throw new PackageManagerException(
10840                            "Packages declaring static-shared libs must target O SDK or higher");
10841                }
10842
10843                // Package declaring static a shared lib cannot be instant apps
10844                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10845                    throw new PackageManagerException(
10846                            "Packages declaring static-shared libs cannot be instant apps");
10847                }
10848
10849                // Package declaring static a shared lib cannot be renamed since the package
10850                // name is synthetic and apps can't code around package manager internals.
10851                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10852                    throw new PackageManagerException(
10853                            "Packages declaring static-shared libs cannot be renamed");
10854                }
10855
10856                // Package declaring static a shared lib cannot declare child packages
10857                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10858                    throw new PackageManagerException(
10859                            "Packages declaring static-shared libs cannot have child packages");
10860                }
10861
10862                // Package declaring static a shared lib cannot declare dynamic libs
10863                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10864                    throw new PackageManagerException(
10865                            "Packages declaring static-shared libs cannot declare dynamic libs");
10866                }
10867
10868                // Package declaring static a shared lib cannot declare shared users
10869                if (pkg.mSharedUserId != null) {
10870                    throw new PackageManagerException(
10871                            "Packages declaring static-shared libs cannot declare shared users");
10872                }
10873
10874                // Static shared libs cannot declare activities
10875                if (!pkg.activities.isEmpty()) {
10876                    throw new PackageManagerException(
10877                            "Static shared libs cannot declare activities");
10878                }
10879
10880                // Static shared libs cannot declare services
10881                if (!pkg.services.isEmpty()) {
10882                    throw new PackageManagerException(
10883                            "Static shared libs cannot declare services");
10884                }
10885
10886                // Static shared libs cannot declare providers
10887                if (!pkg.providers.isEmpty()) {
10888                    throw new PackageManagerException(
10889                            "Static shared libs cannot declare content providers");
10890                }
10891
10892                // Static shared libs cannot declare receivers
10893                if (!pkg.receivers.isEmpty()) {
10894                    throw new PackageManagerException(
10895                            "Static shared libs cannot declare broadcast receivers");
10896                }
10897
10898                // Static shared libs cannot declare permission groups
10899                if (!pkg.permissionGroups.isEmpty()) {
10900                    throw new PackageManagerException(
10901                            "Static shared libs cannot declare permission groups");
10902                }
10903
10904                // Static shared libs cannot declare permissions
10905                if (!pkg.permissions.isEmpty()) {
10906                    throw new PackageManagerException(
10907                            "Static shared libs cannot declare permissions");
10908                }
10909
10910                // Static shared libs cannot declare protected broadcasts
10911                if (pkg.protectedBroadcasts != null) {
10912                    throw new PackageManagerException(
10913                            "Static shared libs cannot declare protected broadcasts");
10914                }
10915
10916                // Static shared libs cannot be overlay targets
10917                if (pkg.mOverlayTarget != null) {
10918                    throw new PackageManagerException(
10919                            "Static shared libs cannot be overlay targets");
10920                }
10921
10922                // The version codes must be ordered as lib versions
10923                long minVersionCode = Long.MIN_VALUE;
10924                long maxVersionCode = Long.MAX_VALUE;
10925
10926                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10927                        pkg.staticSharedLibName);
10928                if (versionedLib != null) {
10929                    final int versionCount = versionedLib.size();
10930                    for (int i = 0; i < versionCount; i++) {
10931                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10932                        final long libVersionCode = libInfo.getDeclaringPackage()
10933                                .getLongVersionCode();
10934                        if (libInfo.getLongVersion() <  pkg.staticSharedLibVersion) {
10935                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10936                        } else if (libInfo.getLongVersion() >  pkg.staticSharedLibVersion) {
10937                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10938                        } else {
10939                            minVersionCode = maxVersionCode = libVersionCode;
10940                            break;
10941                        }
10942                    }
10943                }
10944                if (pkg.getLongVersionCode() < minVersionCode
10945                        || pkg.getLongVersionCode() > maxVersionCode) {
10946                    throw new PackageManagerException("Static shared"
10947                            + " lib version codes must be ordered as lib versions");
10948                }
10949            }
10950
10951            // Only privileged apps and updated privileged apps can add child packages.
10952            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10953                if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10954                    throw new PackageManagerException("Only privileged apps can add child "
10955                            + "packages. Ignoring package " + pkg.packageName);
10956                }
10957                final int childCount = pkg.childPackages.size();
10958                for (int i = 0; i < childCount; i++) {
10959                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10960                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10961                            childPkg.packageName)) {
10962                        throw new PackageManagerException("Can't override child of "
10963                                + "another disabled app. Ignoring package " + pkg.packageName);
10964                    }
10965                }
10966            }
10967
10968            // If we're only installing presumed-existing packages, require that the
10969            // scanned APK is both already known and at the path previously established
10970            // for it.  Previously unknown packages we pick up normally, but if we have an
10971            // a priori expectation about this package's install presence, enforce it.
10972            // With a singular exception for new system packages. When an OTA contains
10973            // a new system package, we allow the codepath to change from a system location
10974            // to the user-installed location. If we don't allow this change, any newer,
10975            // user-installed version of the application will be ignored.
10976            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10977                if (mExpectingBetter.containsKey(pkg.packageName)) {
10978                    logCriticalInfo(Log.WARN,
10979                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10980                } else {
10981                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10982                    if (known != null) {
10983                        if (DEBUG_PACKAGE_SCANNING) {
10984                            Log.d(TAG, "Examining " + pkg.codePath
10985                                    + " and requiring known paths " + known.codePathString
10986                                    + " & " + known.resourcePathString);
10987                        }
10988                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10989                                || !pkg.applicationInfo.getResourcePath().equals(
10990                                        known.resourcePathString)) {
10991                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10992                                    "Application package " + pkg.packageName
10993                                    + " found at " + pkg.applicationInfo.getCodePath()
10994                                    + " but expected at " + known.codePathString
10995                                    + "; ignoring.");
10996                        }
10997                    } else {
10998                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10999                                "Application package " + pkg.packageName
11000                                + " not found; ignoring.");
11001                    }
11002                }
11003            }
11004
11005            // Verify that this new package doesn't have any content providers
11006            // that conflict with existing packages.  Only do this if the
11007            // package isn't already installed, since we don't want to break
11008            // things that are installed.
11009            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11010                final int N = pkg.providers.size();
11011                int i;
11012                for (i=0; i<N; i++) {
11013                    PackageParser.Provider p = pkg.providers.get(i);
11014                    if (p.info.authority != null) {
11015                        String names[] = p.info.authority.split(";");
11016                        for (int j = 0; j < names.length; j++) {
11017                            if (mProvidersByAuthority.containsKey(names[j])) {
11018                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11019                                final String otherPackageName =
11020                                        ((other != null && other.getComponentName() != null) ?
11021                                                other.getComponentName().getPackageName() : "?");
11022                                throw new PackageManagerException(
11023                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11024                                        "Can't install because provider name " + names[j]
11025                                                + " (in package " + pkg.applicationInfo.packageName
11026                                                + ") is already used by " + otherPackageName);
11027                            }
11028                        }
11029                    }
11030                }
11031            }
11032
11033            // Verify that packages sharing a user with a privileged app are marked as privileged.
11034            if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) {
11035                SharedUserSetting sharedUserSetting = null;
11036                try {
11037                    sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
11038                } catch (PackageManagerException ignore) {}
11039                if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
11040                    // Exempt SharedUsers signed with the platform key.
11041                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
11042                    if ((platformPkgSetting.signatures.mSigningDetails
11043                            != PackageParser.SigningDetails.UNKNOWN)
11044                            && (compareSignatures(
11045                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11046                                    pkg.mSigningDetails.signatures)
11047                                            != PackageManager.SIGNATURE_MATCH)) {
11048                        throw new PackageManagerException("Apps that share a user with a " +
11049                                "privileged app must themselves be marked as privileged. " +
11050                                pkg.packageName + " shares privileged user " +
11051                                pkg.mSharedUserId + ".");
11052                    }
11053                }
11054            }
11055
11056            // Apply policies specific for runtime resource overlays (RROs).
11057            if (pkg.mOverlayTarget != null) {
11058                // System overlays have some restrictions on their use of the 'static' state.
11059                if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
11060                    // We are scanning a system overlay. This can be the first scan of the
11061                    // system/vendor/oem partition, or an update to the system overlay.
11062                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
11063                        // This must be an update to a system overlay.
11064                        final PackageSetting previousPkg = assertNotNull(
11065                                mSettings.getPackageLPr(pkg.packageName),
11066                                "previous package state not present");
11067
11068                        // Static overlays cannot be updated.
11069                        if (previousPkg.pkg.mOverlayIsStatic) {
11070                            throw new PackageManagerException("Overlay " + pkg.packageName +
11071                                    " is static and cannot be upgraded.");
11072                        // Non-static overlays cannot be converted to static overlays.
11073                        } else if (pkg.mOverlayIsStatic) {
11074                            throw new PackageManagerException("Overlay " + pkg.packageName +
11075                                    " cannot be upgraded into a static overlay.");
11076                        }
11077                    }
11078                } else {
11079                    // The overlay is a non-system overlay. Non-system overlays cannot be static.
11080                    if (pkg.mOverlayIsStatic) {
11081                        throw new PackageManagerException("Overlay " + pkg.packageName +
11082                                " is static but not pre-installed.");
11083                    }
11084
11085                    // The only case where we allow installation of a non-system overlay is when
11086                    // its signature is signed with the platform certificate.
11087                    PackageSetting platformPkgSetting = mSettings.getPackageLPr("android");
11088                    if ((platformPkgSetting.signatures.mSigningDetails
11089                            != PackageParser.SigningDetails.UNKNOWN)
11090                            && (compareSignatures(
11091                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11092                                    pkg.mSigningDetails.signatures)
11093                                            != PackageManager.SIGNATURE_MATCH)) {
11094                        throw new PackageManagerException("Overlay " + pkg.packageName +
11095                                " must be signed with the platform certificate.");
11096                    }
11097                }
11098            }
11099        }
11100    }
11101
11102    private boolean addSharedLibraryLPw(String path, String apk, String name, long version,
11103            int type, String declaringPackageName, long declaringVersionCode) {
11104        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11105        if (versionedLib == null) {
11106            versionedLib = new LongSparseArray<>();
11107            mSharedLibraries.put(name, versionedLib);
11108            if (type == SharedLibraryInfo.TYPE_STATIC) {
11109                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11110            }
11111        } else if (versionedLib.indexOfKey(version) >= 0) {
11112            return false;
11113        }
11114        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11115                version, type, declaringPackageName, declaringVersionCode);
11116        versionedLib.put(version, libEntry);
11117        return true;
11118    }
11119
11120    private boolean removeSharedLibraryLPw(String name, long version) {
11121        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11122        if (versionedLib == null) {
11123            return false;
11124        }
11125        final int libIdx = versionedLib.indexOfKey(version);
11126        if (libIdx < 0) {
11127            return false;
11128        }
11129        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11130        versionedLib.remove(version);
11131        if (versionedLib.size() <= 0) {
11132            mSharedLibraries.remove(name);
11133            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11134                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11135                        .getPackageName());
11136            }
11137        }
11138        return true;
11139    }
11140
11141    /**
11142     * Adds a scanned package to the system. When this method is finished, the package will
11143     * be available for query, resolution, etc...
11144     */
11145    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11146            UserHandle user, final @ScanFlags int scanFlags, boolean chatty) {
11147        final String pkgName = pkg.packageName;
11148        if (mCustomResolverComponentName != null &&
11149                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11150            setUpCustomResolverActivity(pkg);
11151        }
11152
11153        if (pkg.packageName.equals("android")) {
11154            synchronized (mPackages) {
11155                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11156                    // Set up information for our fall-back user intent resolution activity.
11157                    mPlatformPackage = pkg;
11158                    pkg.mVersionCode = mSdkVersion;
11159                    pkg.mVersionCodeMajor = 0;
11160                    mAndroidApplication = pkg.applicationInfo;
11161                    if (!mResolverReplaced) {
11162                        mResolveActivity.applicationInfo = mAndroidApplication;
11163                        mResolveActivity.name = ResolverActivity.class.getName();
11164                        mResolveActivity.packageName = mAndroidApplication.packageName;
11165                        mResolveActivity.processName = "system:ui";
11166                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11167                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11168                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11169                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11170                        mResolveActivity.exported = true;
11171                        mResolveActivity.enabled = true;
11172                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11173                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11174                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11175                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11176                                | ActivityInfo.CONFIG_ORIENTATION
11177                                | ActivityInfo.CONFIG_KEYBOARD
11178                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11179                        mResolveInfo.activityInfo = mResolveActivity;
11180                        mResolveInfo.priority = 0;
11181                        mResolveInfo.preferredOrder = 0;
11182                        mResolveInfo.match = 0;
11183                        mResolveComponentName = new ComponentName(
11184                                mAndroidApplication.packageName, mResolveActivity.name);
11185                    }
11186                }
11187            }
11188        }
11189
11190        ArrayList<PackageParser.Package> clientLibPkgs = null;
11191        // writer
11192        synchronized (mPackages) {
11193            boolean hasStaticSharedLibs = false;
11194
11195            // Any app can add new static shared libraries
11196            if (pkg.staticSharedLibName != null) {
11197                // Static shared libs don't allow renaming as they have synthetic package
11198                // names to allow install of multiple versions, so use name from manifest.
11199                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11200                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11201                        pkg.manifestPackageName, pkg.getLongVersionCode())) {
11202                    hasStaticSharedLibs = true;
11203                } else {
11204                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11205                                + pkg.staticSharedLibName + " already exists; skipping");
11206                }
11207                // Static shared libs cannot be updated once installed since they
11208                // use synthetic package name which includes the version code, so
11209                // not need to update other packages's shared lib dependencies.
11210            }
11211
11212            if (!hasStaticSharedLibs
11213                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11214                // Only system apps can add new dynamic shared libraries.
11215                if (pkg.libraryNames != null) {
11216                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11217                        String name = pkg.libraryNames.get(i);
11218                        boolean allowed = false;
11219                        if (pkg.isUpdatedSystemApp()) {
11220                            // New library entries can only be added through the
11221                            // system image.  This is important to get rid of a lot
11222                            // of nasty edge cases: for example if we allowed a non-
11223                            // system update of the app to add a library, then uninstalling
11224                            // the update would make the library go away, and assumptions
11225                            // we made such as through app install filtering would now
11226                            // have allowed apps on the device which aren't compatible
11227                            // with it.  Better to just have the restriction here, be
11228                            // conservative, and create many fewer cases that can negatively
11229                            // impact the user experience.
11230                            final PackageSetting sysPs = mSettings
11231                                    .getDisabledSystemPkgLPr(pkg.packageName);
11232                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11233                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11234                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11235                                        allowed = true;
11236                                        break;
11237                                    }
11238                                }
11239                            }
11240                        } else {
11241                            allowed = true;
11242                        }
11243                        if (allowed) {
11244                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11245                                    SharedLibraryInfo.VERSION_UNDEFINED,
11246                                    SharedLibraryInfo.TYPE_DYNAMIC,
11247                                    pkg.packageName, pkg.getLongVersionCode())) {
11248                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11249                                        + name + " already exists; skipping");
11250                            }
11251                        } else {
11252                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11253                                    + name + " that is not declared on system image; skipping");
11254                        }
11255                    }
11256
11257                    if ((scanFlags & SCAN_BOOTING) == 0) {
11258                        // If we are not booting, we need to update any applications
11259                        // that are clients of our shared library.  If we are booting,
11260                        // this will all be done once the scan is complete.
11261                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11262                    }
11263                }
11264            }
11265        }
11266
11267        if ((scanFlags & SCAN_BOOTING) != 0) {
11268            // No apps can run during boot scan, so they don't need to be frozen
11269        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11270            // Caller asked to not kill app, so it's probably not frozen
11271        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11272            // Caller asked us to ignore frozen check for some reason; they
11273            // probably didn't know the package name
11274        } else {
11275            // We're doing major surgery on this package, so it better be frozen
11276            // right now to keep it from launching
11277            checkPackageFrozen(pkgName);
11278        }
11279
11280        // Also need to kill any apps that are dependent on the library.
11281        if (clientLibPkgs != null) {
11282            for (int i=0; i<clientLibPkgs.size(); i++) {
11283                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11284                killApplication(clientPkg.applicationInfo.packageName,
11285                        clientPkg.applicationInfo.uid, "update lib");
11286            }
11287        }
11288
11289        // writer
11290        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11291
11292        synchronized (mPackages) {
11293            // We don't expect installation to fail beyond this point
11294
11295            // Add the new setting to mSettings
11296            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11297            // Add the new setting to mPackages
11298            mPackages.put(pkg.applicationInfo.packageName, pkg);
11299            // Make sure we don't accidentally delete its data.
11300            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11301            while (iter.hasNext()) {
11302                PackageCleanItem item = iter.next();
11303                if (pkgName.equals(item.packageName)) {
11304                    iter.remove();
11305                }
11306            }
11307
11308            // Add the package's KeySets to the global KeySetManagerService
11309            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11310            ksms.addScannedPackageLPw(pkg);
11311
11312            int N = pkg.providers.size();
11313            StringBuilder r = null;
11314            int i;
11315            for (i=0; i<N; i++) {
11316                PackageParser.Provider p = pkg.providers.get(i);
11317                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11318                        p.info.processName);
11319                mProviders.addProvider(p);
11320                p.syncable = p.info.isSyncable;
11321                if (p.info.authority != null) {
11322                    String names[] = p.info.authority.split(";");
11323                    p.info.authority = null;
11324                    for (int j = 0; j < names.length; j++) {
11325                        if (j == 1 && p.syncable) {
11326                            // We only want the first authority for a provider to possibly be
11327                            // syncable, so if we already added this provider using a different
11328                            // authority clear the syncable flag. We copy the provider before
11329                            // changing it because the mProviders object contains a reference
11330                            // to a provider that we don't want to change.
11331                            // Only do this for the second authority since the resulting provider
11332                            // object can be the same for all future authorities for this provider.
11333                            p = new PackageParser.Provider(p);
11334                            p.syncable = false;
11335                        }
11336                        if (!mProvidersByAuthority.containsKey(names[j])) {
11337                            mProvidersByAuthority.put(names[j], p);
11338                            if (p.info.authority == null) {
11339                                p.info.authority = names[j];
11340                            } else {
11341                                p.info.authority = p.info.authority + ";" + names[j];
11342                            }
11343                            if (DEBUG_PACKAGE_SCANNING) {
11344                                if (chatty)
11345                                    Log.d(TAG, "Registered content provider: " + names[j]
11346                                            + ", className = " + p.info.name + ", isSyncable = "
11347                                            + p.info.isSyncable);
11348                            }
11349                        } else {
11350                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11351                            Slog.w(TAG, "Skipping provider name " + names[j] +
11352                                    " (in package " + pkg.applicationInfo.packageName +
11353                                    "): name already used by "
11354                                    + ((other != null && other.getComponentName() != null)
11355                                            ? other.getComponentName().getPackageName() : "?"));
11356                        }
11357                    }
11358                }
11359                if (chatty) {
11360                    if (r == null) {
11361                        r = new StringBuilder(256);
11362                    } else {
11363                        r.append(' ');
11364                    }
11365                    r.append(p.info.name);
11366                }
11367            }
11368            if (r != null) {
11369                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11370            }
11371
11372            N = pkg.services.size();
11373            r = null;
11374            for (i=0; i<N; i++) {
11375                PackageParser.Service s = pkg.services.get(i);
11376                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11377                        s.info.processName);
11378                mServices.addService(s);
11379                if (chatty) {
11380                    if (r == null) {
11381                        r = new StringBuilder(256);
11382                    } else {
11383                        r.append(' ');
11384                    }
11385                    r.append(s.info.name);
11386                }
11387            }
11388            if (r != null) {
11389                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11390            }
11391
11392            N = pkg.receivers.size();
11393            r = null;
11394            for (i=0; i<N; i++) {
11395                PackageParser.Activity a = pkg.receivers.get(i);
11396                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11397                        a.info.processName);
11398                mReceivers.addActivity(a, "receiver");
11399                if (chatty) {
11400                    if (r == null) {
11401                        r = new StringBuilder(256);
11402                    } else {
11403                        r.append(' ');
11404                    }
11405                    r.append(a.info.name);
11406                }
11407            }
11408            if (r != null) {
11409                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11410            }
11411
11412            N = pkg.activities.size();
11413            r = null;
11414            for (i=0; i<N; i++) {
11415                PackageParser.Activity a = pkg.activities.get(i);
11416                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11417                        a.info.processName);
11418                mActivities.addActivity(a, "activity");
11419                if (chatty) {
11420                    if (r == null) {
11421                        r = new StringBuilder(256);
11422                    } else {
11423                        r.append(' ');
11424                    }
11425                    r.append(a.info.name);
11426                }
11427            }
11428            if (r != null) {
11429                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11430            }
11431
11432            // Don't allow ephemeral applications to define new permissions groups.
11433            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11434                Slog.w(TAG, "Permission groups from package " + pkg.packageName
11435                        + " ignored: instant apps cannot define new permission groups.");
11436            } else {
11437                mPermissionManager.addAllPermissionGroups(pkg, chatty);
11438            }
11439
11440            // Don't allow ephemeral applications to define new permissions.
11441            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11442                Slog.w(TAG, "Permissions from package " + pkg.packageName
11443                        + " ignored: instant apps cannot define new permissions.");
11444            } else {
11445                mPermissionManager.addAllPermissions(pkg, chatty);
11446            }
11447
11448            N = pkg.instrumentation.size();
11449            r = null;
11450            for (i=0; i<N; i++) {
11451                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11452                a.info.packageName = pkg.applicationInfo.packageName;
11453                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11454                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11455                a.info.splitNames = pkg.splitNames;
11456                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11457                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11458                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11459                a.info.dataDir = pkg.applicationInfo.dataDir;
11460                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11461                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11462                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11463                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11464                mInstrumentation.put(a.getComponentName(), a);
11465                if (chatty) {
11466                    if (r == null) {
11467                        r = new StringBuilder(256);
11468                    } else {
11469                        r.append(' ');
11470                    }
11471                    r.append(a.info.name);
11472                }
11473            }
11474            if (r != null) {
11475                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11476            }
11477
11478            if (pkg.protectedBroadcasts != null) {
11479                N = pkg.protectedBroadcasts.size();
11480                synchronized (mProtectedBroadcasts) {
11481                    for (i = 0; i < N; i++) {
11482                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11483                    }
11484                }
11485            }
11486        }
11487
11488        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11489    }
11490
11491    /**
11492     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11493     * is derived purely on the basis of the contents of {@code scanFile} and
11494     * {@code cpuAbiOverride}.
11495     *
11496     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11497     */
11498    private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride,
11499            boolean extractLibs)
11500                    throws PackageManagerException {
11501        // Give ourselves some initial paths; we'll come back for another
11502        // pass once we've determined ABI below.
11503        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11504
11505        // We would never need to extract libs for forward-locked and external packages,
11506        // since the container service will do it for us. We shouldn't attempt to
11507        // extract libs from system app when it was not updated.
11508        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11509                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11510            extractLibs = false;
11511        }
11512
11513        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11514        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11515
11516        NativeLibraryHelper.Handle handle = null;
11517        try {
11518            handle = NativeLibraryHelper.Handle.create(pkg);
11519            // TODO(multiArch): This can be null for apps that didn't go through the
11520            // usual installation process. We can calculate it again, like we
11521            // do during install time.
11522            //
11523            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11524            // unnecessary.
11525            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11526
11527            // Null out the abis so that they can be recalculated.
11528            pkg.applicationInfo.primaryCpuAbi = null;
11529            pkg.applicationInfo.secondaryCpuAbi = null;
11530            if (isMultiArch(pkg.applicationInfo)) {
11531                // Warn if we've set an abiOverride for multi-lib packages..
11532                // By definition, we need to copy both 32 and 64 bit libraries for
11533                // such packages.
11534                if (pkg.cpuAbiOverride != null
11535                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11536                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11537                }
11538
11539                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11540                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11541                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11542                    if (extractLibs) {
11543                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11544                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11545                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11546                                useIsaSpecificSubdirs);
11547                    } else {
11548                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11549                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11550                    }
11551                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11552                }
11553
11554                // Shared library native code should be in the APK zip aligned
11555                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11556                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11557                            "Shared library native lib extraction not supported");
11558                }
11559
11560                maybeThrowExceptionForMultiArchCopy(
11561                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11562
11563                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11564                    if (extractLibs) {
11565                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11566                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11567                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11568                                useIsaSpecificSubdirs);
11569                    } else {
11570                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11571                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11572                    }
11573                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11574                }
11575
11576                maybeThrowExceptionForMultiArchCopy(
11577                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11578
11579                if (abi64 >= 0) {
11580                    // Shared library native libs should be in the APK zip aligned
11581                    if (extractLibs && pkg.isLibrary()) {
11582                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11583                                "Shared library native lib extraction not supported");
11584                    }
11585                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11586                }
11587
11588                if (abi32 >= 0) {
11589                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11590                    if (abi64 >= 0) {
11591                        if (pkg.use32bitAbi) {
11592                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11593                            pkg.applicationInfo.primaryCpuAbi = abi;
11594                        } else {
11595                            pkg.applicationInfo.secondaryCpuAbi = abi;
11596                        }
11597                    } else {
11598                        pkg.applicationInfo.primaryCpuAbi = abi;
11599                    }
11600                }
11601            } else {
11602                String[] abiList = (cpuAbiOverride != null) ?
11603                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11604
11605                // Enable gross and lame hacks for apps that are built with old
11606                // SDK tools. We must scan their APKs for renderscript bitcode and
11607                // not launch them if it's present. Don't bother checking on devices
11608                // that don't have 64 bit support.
11609                boolean needsRenderScriptOverride = false;
11610                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11611                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11612                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11613                    needsRenderScriptOverride = true;
11614                }
11615
11616                final int copyRet;
11617                if (extractLibs) {
11618                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11619                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11620                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11621                } else {
11622                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11623                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11624                }
11625                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11626
11627                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11628                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11629                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11630                }
11631
11632                if (copyRet >= 0) {
11633                    // Shared libraries that have native libs must be multi-architecture
11634                    if (pkg.isLibrary()) {
11635                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11636                                "Shared library with native libs must be multiarch");
11637                    }
11638                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11639                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11640                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11641                } else if (needsRenderScriptOverride) {
11642                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11643                }
11644            }
11645        } catch (IOException ioe) {
11646            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11647        } finally {
11648            IoUtils.closeQuietly(handle);
11649        }
11650
11651        // Now that we've calculated the ABIs and determined if it's an internal app,
11652        // we will go ahead and populate the nativeLibraryPath.
11653        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11654    }
11655
11656    /**
11657     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11658     * i.e, so that all packages can be run inside a single process if required.
11659     *
11660     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11661     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11662     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11663     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11664     * updating a package that belongs to a shared user.
11665     *
11666     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11667     * adds unnecessary complexity.
11668     */
11669    private static @Nullable List<String> adjustCpuAbisForSharedUserLPw(
11670            Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) {
11671        List<String> changedAbiCodePath = null;
11672        String requiredInstructionSet = null;
11673        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11674            requiredInstructionSet = VMRuntime.getInstructionSet(
11675                     scannedPackage.applicationInfo.primaryCpuAbi);
11676        }
11677
11678        PackageSetting requirer = null;
11679        for (PackageSetting ps : packagesForUser) {
11680            // If packagesForUser contains scannedPackage, we skip it. This will happen
11681            // when scannedPackage is an update of an existing package. Without this check,
11682            // we will never be able to change the ABI of any package belonging to a shared
11683            // user, even if it's compatible with other packages.
11684            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11685                if (ps.primaryCpuAbiString == null) {
11686                    continue;
11687                }
11688
11689                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11690                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11691                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11692                    // this but there's not much we can do.
11693                    String errorMessage = "Instruction set mismatch, "
11694                            + ((requirer == null) ? "[caller]" : requirer)
11695                            + " requires " + requiredInstructionSet + " whereas " + ps
11696                            + " requires " + instructionSet;
11697                    Slog.w(TAG, errorMessage);
11698                }
11699
11700                if (requiredInstructionSet == null) {
11701                    requiredInstructionSet = instructionSet;
11702                    requirer = ps;
11703                }
11704            }
11705        }
11706
11707        if (requiredInstructionSet != null) {
11708            String adjustedAbi;
11709            if (requirer != null) {
11710                // requirer != null implies that either scannedPackage was null or that scannedPackage
11711                // did not require an ABI, in which case we have to adjust scannedPackage to match
11712                // the ABI of the set (which is the same as requirer's ABI)
11713                adjustedAbi = requirer.primaryCpuAbiString;
11714                if (scannedPackage != null) {
11715                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11716                }
11717            } else {
11718                // requirer == null implies that we're updating all ABIs in the set to
11719                // match scannedPackage.
11720                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11721            }
11722
11723            for (PackageSetting ps : packagesForUser) {
11724                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11725                    if (ps.primaryCpuAbiString != null) {
11726                        continue;
11727                    }
11728
11729                    ps.primaryCpuAbiString = adjustedAbi;
11730                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11731                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11732                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11733                        if (DEBUG_ABI_SELECTION) {
11734                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11735                                    + " (requirer="
11736                                    + (requirer != null ? requirer.pkg : "null")
11737                                    + ", scannedPackage="
11738                                    + (scannedPackage != null ? scannedPackage : "null")
11739                                    + ")");
11740                        }
11741                        if (changedAbiCodePath == null) {
11742                            changedAbiCodePath = new ArrayList<>();
11743                        }
11744                        changedAbiCodePath.add(ps.codePathString);
11745                    }
11746                }
11747            }
11748        }
11749        return changedAbiCodePath;
11750    }
11751
11752    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11753        synchronized (mPackages) {
11754            mResolverReplaced = true;
11755            // Set up information for custom user intent resolution activity.
11756            mResolveActivity.applicationInfo = pkg.applicationInfo;
11757            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11758            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11759            mResolveActivity.processName = pkg.applicationInfo.packageName;
11760            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11761            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11762                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11763            mResolveActivity.theme = 0;
11764            mResolveActivity.exported = true;
11765            mResolveActivity.enabled = true;
11766            mResolveInfo.activityInfo = mResolveActivity;
11767            mResolveInfo.priority = 0;
11768            mResolveInfo.preferredOrder = 0;
11769            mResolveInfo.match = 0;
11770            mResolveComponentName = mCustomResolverComponentName;
11771            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11772                    mResolveComponentName);
11773        }
11774    }
11775
11776    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11777        if (installerActivity == null) {
11778            if (DEBUG_INSTANT) {
11779                Slog.d(TAG, "Clear ephemeral installer activity");
11780            }
11781            mInstantAppInstallerActivity = null;
11782            return;
11783        }
11784
11785        if (DEBUG_INSTANT) {
11786            Slog.d(TAG, "Set ephemeral installer activity: "
11787                    + installerActivity.getComponentName());
11788        }
11789        // Set up information for ephemeral installer activity
11790        mInstantAppInstallerActivity = installerActivity;
11791        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11792                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11793        mInstantAppInstallerActivity.exported = true;
11794        mInstantAppInstallerActivity.enabled = true;
11795        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11796        mInstantAppInstallerInfo.priority = 1;
11797        mInstantAppInstallerInfo.preferredOrder = 1;
11798        mInstantAppInstallerInfo.isDefault = true;
11799        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11800                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11801    }
11802
11803    private static String calculateBundledApkRoot(final String codePathString) {
11804        final File codePath = new File(codePathString);
11805        final File codeRoot;
11806        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11807            codeRoot = Environment.getRootDirectory();
11808        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11809            codeRoot = Environment.getOemDirectory();
11810        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11811            codeRoot = Environment.getVendorDirectory();
11812        } else if (FileUtils.contains(Environment.getOdmDirectory(), codePath)) {
11813            codeRoot = Environment.getOdmDirectory();
11814        } else if (FileUtils.contains(Environment.getProductDirectory(), codePath)) {
11815            codeRoot = Environment.getProductDirectory();
11816        } else {
11817            // Unrecognized code path; take its top real segment as the apk root:
11818            // e.g. /something/app/blah.apk => /something
11819            try {
11820                File f = codePath.getCanonicalFile();
11821                File parent = f.getParentFile();    // non-null because codePath is a file
11822                File tmp;
11823                while ((tmp = parent.getParentFile()) != null) {
11824                    f = parent;
11825                    parent = tmp;
11826                }
11827                codeRoot = f;
11828                Slog.w(TAG, "Unrecognized code path "
11829                        + codePath + " - using " + codeRoot);
11830            } catch (IOException e) {
11831                // Can't canonicalize the code path -- shenanigans?
11832                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11833                return Environment.getRootDirectory().getPath();
11834            }
11835        }
11836        return codeRoot.getPath();
11837    }
11838
11839    /**
11840     * Derive and set the location of native libraries for the given package,
11841     * which varies depending on where and how the package was installed.
11842     */
11843    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11844        final ApplicationInfo info = pkg.applicationInfo;
11845        final String codePath = pkg.codePath;
11846        final File codeFile = new File(codePath);
11847        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11848        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11849
11850        info.nativeLibraryRootDir = null;
11851        info.nativeLibraryRootRequiresIsa = false;
11852        info.nativeLibraryDir = null;
11853        info.secondaryNativeLibraryDir = null;
11854
11855        if (isApkFile(codeFile)) {
11856            // Monolithic install
11857            if (bundledApp) {
11858                // If "/system/lib64/apkname" exists, assume that is the per-package
11859                // native library directory to use; otherwise use "/system/lib/apkname".
11860                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11861                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11862                        getPrimaryInstructionSet(info));
11863
11864                // This is a bundled system app so choose the path based on the ABI.
11865                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11866                // is just the default path.
11867                final String apkName = deriveCodePathName(codePath);
11868                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11869                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11870                        apkName).getAbsolutePath();
11871
11872                if (info.secondaryCpuAbi != null) {
11873                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11874                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11875                            secondaryLibDir, apkName).getAbsolutePath();
11876                }
11877            } else if (asecApp) {
11878                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11879                        .getAbsolutePath();
11880            } else {
11881                final String apkName = deriveCodePathName(codePath);
11882                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11883                        .getAbsolutePath();
11884            }
11885
11886            info.nativeLibraryRootRequiresIsa = false;
11887            info.nativeLibraryDir = info.nativeLibraryRootDir;
11888        } else {
11889            // Cluster install
11890            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11891            info.nativeLibraryRootRequiresIsa = true;
11892
11893            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11894                    getPrimaryInstructionSet(info)).getAbsolutePath();
11895
11896            if (info.secondaryCpuAbi != null) {
11897                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11898                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11899            }
11900        }
11901    }
11902
11903    /**
11904     * Calculate the abis and roots for a bundled app. These can uniquely
11905     * be determined from the contents of the system partition, i.e whether
11906     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11907     * of this information, and instead assume that the system was built
11908     * sensibly.
11909     */
11910    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11911                                           PackageSetting pkgSetting) {
11912        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11913
11914        // If "/system/lib64/apkname" exists, assume that is the per-package
11915        // native library directory to use; otherwise use "/system/lib/apkname".
11916        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11917        setBundledAppAbi(pkg, apkRoot, apkName);
11918        // pkgSetting might be null during rescan following uninstall of updates
11919        // to a bundled app, so accommodate that possibility.  The settings in
11920        // that case will be established later from the parsed package.
11921        //
11922        // If the settings aren't null, sync them up with what we've just derived.
11923        // note that apkRoot isn't stored in the package settings.
11924        if (pkgSetting != null) {
11925            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11926            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11927        }
11928    }
11929
11930    /**
11931     * Deduces the ABI of a bundled app and sets the relevant fields on the
11932     * parsed pkg object.
11933     *
11934     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11935     *        under which system libraries are installed.
11936     * @param apkName the name of the installed package.
11937     */
11938    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11939        final File codeFile = new File(pkg.codePath);
11940
11941        final boolean has64BitLibs;
11942        final boolean has32BitLibs;
11943        if (isApkFile(codeFile)) {
11944            // Monolithic install
11945            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11946            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11947        } else {
11948            // Cluster install
11949            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11950            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11951                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11952                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11953                has64BitLibs = (new File(rootDir, isa)).exists();
11954            } else {
11955                has64BitLibs = false;
11956            }
11957            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11958                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11959                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11960                has32BitLibs = (new File(rootDir, isa)).exists();
11961            } else {
11962                has32BitLibs = false;
11963            }
11964        }
11965
11966        if (has64BitLibs && !has32BitLibs) {
11967            // The package has 64 bit libs, but not 32 bit libs. Its primary
11968            // ABI should be 64 bit. We can safely assume here that the bundled
11969            // native libraries correspond to the most preferred ABI in the list.
11970
11971            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11972            pkg.applicationInfo.secondaryCpuAbi = null;
11973        } else if (has32BitLibs && !has64BitLibs) {
11974            // The package has 32 bit libs but not 64 bit libs. Its primary
11975            // ABI should be 32 bit.
11976
11977            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11978            pkg.applicationInfo.secondaryCpuAbi = null;
11979        } else if (has32BitLibs && has64BitLibs) {
11980            // The application has both 64 and 32 bit bundled libraries. We check
11981            // here that the app declares multiArch support, and warn if it doesn't.
11982            //
11983            // We will be lenient here and record both ABIs. The primary will be the
11984            // ABI that's higher on the list, i.e, a device that's configured to prefer
11985            // 64 bit apps will see a 64 bit primary ABI,
11986
11987            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11988                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11989            }
11990
11991            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11992                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11993                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11994            } else {
11995                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11996                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11997            }
11998        } else {
11999            pkg.applicationInfo.primaryCpuAbi = null;
12000            pkg.applicationInfo.secondaryCpuAbi = null;
12001        }
12002    }
12003
12004    private void killApplication(String pkgName, int appId, String reason) {
12005        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12006    }
12007
12008    private void killApplication(String pkgName, int appId, int userId, String reason) {
12009        // Request the ActivityManager to kill the process(only for existing packages)
12010        // so that we do not end up in a confused state while the user is still using the older
12011        // version of the application while the new one gets installed.
12012        final long token = Binder.clearCallingIdentity();
12013        try {
12014            IActivityManager am = ActivityManager.getService();
12015            if (am != null) {
12016                try {
12017                    am.killApplication(pkgName, appId, userId, reason);
12018                } catch (RemoteException e) {
12019                }
12020            }
12021        } finally {
12022            Binder.restoreCallingIdentity(token);
12023        }
12024    }
12025
12026    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12027        // Remove the parent package setting
12028        PackageSetting ps = (PackageSetting) pkg.mExtras;
12029        if (ps != null) {
12030            removePackageLI(ps, chatty);
12031        }
12032        // Remove the child package setting
12033        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12034        for (int i = 0; i < childCount; i++) {
12035            PackageParser.Package childPkg = pkg.childPackages.get(i);
12036            ps = (PackageSetting) childPkg.mExtras;
12037            if (ps != null) {
12038                removePackageLI(ps, chatty);
12039            }
12040        }
12041    }
12042
12043    void removePackageLI(PackageSetting ps, boolean chatty) {
12044        if (DEBUG_INSTALL) {
12045            if (chatty)
12046                Log.d(TAG, "Removing package " + ps.name);
12047        }
12048
12049        // writer
12050        synchronized (mPackages) {
12051            mPackages.remove(ps.name);
12052            final PackageParser.Package pkg = ps.pkg;
12053            if (pkg != null) {
12054                cleanPackageDataStructuresLILPw(pkg, chatty);
12055            }
12056        }
12057    }
12058
12059    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12060        if (DEBUG_INSTALL) {
12061            if (chatty)
12062                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12063        }
12064
12065        // writer
12066        synchronized (mPackages) {
12067            // Remove the parent package
12068            mPackages.remove(pkg.applicationInfo.packageName);
12069            cleanPackageDataStructuresLILPw(pkg, chatty);
12070
12071            // Remove the child packages
12072            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12073            for (int i = 0; i < childCount; i++) {
12074                PackageParser.Package childPkg = pkg.childPackages.get(i);
12075                mPackages.remove(childPkg.applicationInfo.packageName);
12076                cleanPackageDataStructuresLILPw(childPkg, chatty);
12077            }
12078        }
12079    }
12080
12081    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12082        int N = pkg.providers.size();
12083        StringBuilder r = null;
12084        int i;
12085        for (i=0; i<N; i++) {
12086            PackageParser.Provider p = pkg.providers.get(i);
12087            mProviders.removeProvider(p);
12088            if (p.info.authority == null) {
12089
12090                /* There was another ContentProvider with this authority when
12091                 * this app was installed so this authority is null,
12092                 * Ignore it as we don't have to unregister the provider.
12093                 */
12094                continue;
12095            }
12096            String names[] = p.info.authority.split(";");
12097            for (int j = 0; j < names.length; j++) {
12098                if (mProvidersByAuthority.get(names[j]) == p) {
12099                    mProvidersByAuthority.remove(names[j]);
12100                    if (DEBUG_REMOVE) {
12101                        if (chatty)
12102                            Log.d(TAG, "Unregistered content provider: " + names[j]
12103                                    + ", className = " + p.info.name + ", isSyncable = "
12104                                    + p.info.isSyncable);
12105                    }
12106                }
12107            }
12108            if (DEBUG_REMOVE && chatty) {
12109                if (r == null) {
12110                    r = new StringBuilder(256);
12111                } else {
12112                    r.append(' ');
12113                }
12114                r.append(p.info.name);
12115            }
12116        }
12117        if (r != null) {
12118            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12119        }
12120
12121        N = pkg.services.size();
12122        r = null;
12123        for (i=0; i<N; i++) {
12124            PackageParser.Service s = pkg.services.get(i);
12125            mServices.removeService(s);
12126            if (chatty) {
12127                if (r == null) {
12128                    r = new StringBuilder(256);
12129                } else {
12130                    r.append(' ');
12131                }
12132                r.append(s.info.name);
12133            }
12134        }
12135        if (r != null) {
12136            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12137        }
12138
12139        N = pkg.receivers.size();
12140        r = null;
12141        for (i=0; i<N; i++) {
12142            PackageParser.Activity a = pkg.receivers.get(i);
12143            mReceivers.removeActivity(a, "receiver");
12144            if (DEBUG_REMOVE && chatty) {
12145                if (r == null) {
12146                    r = new StringBuilder(256);
12147                } else {
12148                    r.append(' ');
12149                }
12150                r.append(a.info.name);
12151            }
12152        }
12153        if (r != null) {
12154            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12155        }
12156
12157        N = pkg.activities.size();
12158        r = null;
12159        for (i=0; i<N; i++) {
12160            PackageParser.Activity a = pkg.activities.get(i);
12161            mActivities.removeActivity(a, "activity");
12162            if (DEBUG_REMOVE && chatty) {
12163                if (r == null) {
12164                    r = new StringBuilder(256);
12165                } else {
12166                    r.append(' ');
12167                }
12168                r.append(a.info.name);
12169            }
12170        }
12171        if (r != null) {
12172            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12173        }
12174
12175        mPermissionManager.removeAllPermissions(pkg, chatty);
12176
12177        N = pkg.instrumentation.size();
12178        r = null;
12179        for (i=0; i<N; i++) {
12180            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12181            mInstrumentation.remove(a.getComponentName());
12182            if (DEBUG_REMOVE && chatty) {
12183                if (r == null) {
12184                    r = new StringBuilder(256);
12185                } else {
12186                    r.append(' ');
12187                }
12188                r.append(a.info.name);
12189            }
12190        }
12191        if (r != null) {
12192            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12193        }
12194
12195        r = null;
12196        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12197            // Only system apps can hold shared libraries.
12198            if (pkg.libraryNames != null) {
12199                for (i = 0; i < pkg.libraryNames.size(); i++) {
12200                    String name = pkg.libraryNames.get(i);
12201                    if (removeSharedLibraryLPw(name, 0)) {
12202                        if (DEBUG_REMOVE && chatty) {
12203                            if (r == null) {
12204                                r = new StringBuilder(256);
12205                            } else {
12206                                r.append(' ');
12207                            }
12208                            r.append(name);
12209                        }
12210                    }
12211                }
12212            }
12213        }
12214
12215        r = null;
12216
12217        // Any package can hold static shared libraries.
12218        if (pkg.staticSharedLibName != null) {
12219            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12220                if (DEBUG_REMOVE && chatty) {
12221                    if (r == null) {
12222                        r = new StringBuilder(256);
12223                    } else {
12224                        r.append(' ');
12225                    }
12226                    r.append(pkg.staticSharedLibName);
12227                }
12228            }
12229        }
12230
12231        if (r != null) {
12232            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12233        }
12234    }
12235
12236
12237    final class ActivityIntentResolver
12238            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12239        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12240                boolean defaultOnly, int userId) {
12241            if (!sUserManager.exists(userId)) return null;
12242            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12243            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12244        }
12245
12246        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12247                int userId) {
12248            if (!sUserManager.exists(userId)) return null;
12249            mFlags = flags;
12250            return super.queryIntent(intent, resolvedType,
12251                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12252                    userId);
12253        }
12254
12255        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12256                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12257            if (!sUserManager.exists(userId)) return null;
12258            if (packageActivities == null) {
12259                return null;
12260            }
12261            mFlags = flags;
12262            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12263            final int N = packageActivities.size();
12264            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12265                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12266
12267            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12268            for (int i = 0; i < N; ++i) {
12269                intentFilters = packageActivities.get(i).intents;
12270                if (intentFilters != null && intentFilters.size() > 0) {
12271                    PackageParser.ActivityIntentInfo[] array =
12272                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12273                    intentFilters.toArray(array);
12274                    listCut.add(array);
12275                }
12276            }
12277            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12278        }
12279
12280        /**
12281         * Finds a privileged activity that matches the specified activity names.
12282         */
12283        private PackageParser.Activity findMatchingActivity(
12284                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12285            for (PackageParser.Activity sysActivity : activityList) {
12286                if (sysActivity.info.name.equals(activityInfo.name)) {
12287                    return sysActivity;
12288                }
12289                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12290                    return sysActivity;
12291                }
12292                if (sysActivity.info.targetActivity != null) {
12293                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12294                        return sysActivity;
12295                    }
12296                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12297                        return sysActivity;
12298                    }
12299                }
12300            }
12301            return null;
12302        }
12303
12304        public class IterGenerator<E> {
12305            public Iterator<E> generate(ActivityIntentInfo info) {
12306                return null;
12307            }
12308        }
12309
12310        public class ActionIterGenerator extends IterGenerator<String> {
12311            @Override
12312            public Iterator<String> generate(ActivityIntentInfo info) {
12313                return info.actionsIterator();
12314            }
12315        }
12316
12317        public class CategoriesIterGenerator extends IterGenerator<String> {
12318            @Override
12319            public Iterator<String> generate(ActivityIntentInfo info) {
12320                return info.categoriesIterator();
12321            }
12322        }
12323
12324        public class SchemesIterGenerator extends IterGenerator<String> {
12325            @Override
12326            public Iterator<String> generate(ActivityIntentInfo info) {
12327                return info.schemesIterator();
12328            }
12329        }
12330
12331        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12332            @Override
12333            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12334                return info.authoritiesIterator();
12335            }
12336        }
12337
12338        /**
12339         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12340         * MODIFIED. Do not pass in a list that should not be changed.
12341         */
12342        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12343                IterGenerator<T> generator, Iterator<T> searchIterator) {
12344            // loop through the set of actions; every one must be found in the intent filter
12345            while (searchIterator.hasNext()) {
12346                // we must have at least one filter in the list to consider a match
12347                if (intentList.size() == 0) {
12348                    break;
12349                }
12350
12351                final T searchAction = searchIterator.next();
12352
12353                // loop through the set of intent filters
12354                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12355                while (intentIter.hasNext()) {
12356                    final ActivityIntentInfo intentInfo = intentIter.next();
12357                    boolean selectionFound = false;
12358
12359                    // loop through the intent filter's selection criteria; at least one
12360                    // of them must match the searched criteria
12361                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12362                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12363                        final T intentSelection = intentSelectionIter.next();
12364                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12365                            selectionFound = true;
12366                            break;
12367                        }
12368                    }
12369
12370                    // the selection criteria wasn't found in this filter's set; this filter
12371                    // is not a potential match
12372                    if (!selectionFound) {
12373                        intentIter.remove();
12374                    }
12375                }
12376            }
12377        }
12378
12379        private boolean isProtectedAction(ActivityIntentInfo filter) {
12380            final Iterator<String> actionsIter = filter.actionsIterator();
12381            while (actionsIter != null && actionsIter.hasNext()) {
12382                final String filterAction = actionsIter.next();
12383                if (PROTECTED_ACTIONS.contains(filterAction)) {
12384                    return true;
12385                }
12386            }
12387            return false;
12388        }
12389
12390        /**
12391         * Adjusts the priority of the given intent filter according to policy.
12392         * <p>
12393         * <ul>
12394         * <li>The priority for non privileged applications is capped to '0'</li>
12395         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12396         * <li>The priority for unbundled updates to privileged applications is capped to the
12397         *      priority defined on the system partition</li>
12398         * </ul>
12399         * <p>
12400         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12401         * allowed to obtain any priority on any action.
12402         */
12403        private void adjustPriority(
12404                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12405            // nothing to do; priority is fine as-is
12406            if (intent.getPriority() <= 0) {
12407                return;
12408            }
12409
12410            final ActivityInfo activityInfo = intent.activity.info;
12411            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12412
12413            final boolean privilegedApp =
12414                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12415            if (!privilegedApp) {
12416                // non-privileged applications can never define a priority >0
12417                if (DEBUG_FILTERS) {
12418                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12419                            + " package: " + applicationInfo.packageName
12420                            + " activity: " + intent.activity.className
12421                            + " origPrio: " + intent.getPriority());
12422                }
12423                intent.setPriority(0);
12424                return;
12425            }
12426
12427            if (systemActivities == null) {
12428                // the system package is not disabled; we're parsing the system partition
12429                if (isProtectedAction(intent)) {
12430                    if (mDeferProtectedFilters) {
12431                        // We can't deal with these just yet. No component should ever obtain a
12432                        // >0 priority for a protected actions, with ONE exception -- the setup
12433                        // wizard. The setup wizard, however, cannot be known until we're able to
12434                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12435                        // until all intent filters have been processed. Chicken, meet egg.
12436                        // Let the filter temporarily have a high priority and rectify the
12437                        // priorities after all system packages have been scanned.
12438                        mProtectedFilters.add(intent);
12439                        if (DEBUG_FILTERS) {
12440                            Slog.i(TAG, "Protected action; save for later;"
12441                                    + " package: " + applicationInfo.packageName
12442                                    + " activity: " + intent.activity.className
12443                                    + " origPrio: " + intent.getPriority());
12444                        }
12445                        return;
12446                    } else {
12447                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12448                            Slog.i(TAG, "No setup wizard;"
12449                                + " All protected intents capped to priority 0");
12450                        }
12451                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12452                            if (DEBUG_FILTERS) {
12453                                Slog.i(TAG, "Found setup wizard;"
12454                                    + " allow priority " + intent.getPriority() + ";"
12455                                    + " package: " + intent.activity.info.packageName
12456                                    + " activity: " + intent.activity.className
12457                                    + " priority: " + intent.getPriority());
12458                            }
12459                            // setup wizard gets whatever it wants
12460                            return;
12461                        }
12462                        if (DEBUG_FILTERS) {
12463                            Slog.i(TAG, "Protected action; cap priority to 0;"
12464                                    + " package: " + intent.activity.info.packageName
12465                                    + " activity: " + intent.activity.className
12466                                    + " origPrio: " + intent.getPriority());
12467                        }
12468                        intent.setPriority(0);
12469                        return;
12470                    }
12471                }
12472                // privileged apps on the system image get whatever priority they request
12473                return;
12474            }
12475
12476            // privileged app unbundled update ... try to find the same activity
12477            final PackageParser.Activity foundActivity =
12478                    findMatchingActivity(systemActivities, activityInfo);
12479            if (foundActivity == null) {
12480                // this is a new activity; it cannot obtain >0 priority
12481                if (DEBUG_FILTERS) {
12482                    Slog.i(TAG, "New activity; cap priority to 0;"
12483                            + " package: " + applicationInfo.packageName
12484                            + " activity: " + intent.activity.className
12485                            + " origPrio: " + intent.getPriority());
12486                }
12487                intent.setPriority(0);
12488                return;
12489            }
12490
12491            // found activity, now check for filter equivalence
12492
12493            // a shallow copy is enough; we modify the list, not its contents
12494            final List<ActivityIntentInfo> intentListCopy =
12495                    new ArrayList<>(foundActivity.intents);
12496            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12497
12498            // find matching action subsets
12499            final Iterator<String> actionsIterator = intent.actionsIterator();
12500            if (actionsIterator != null) {
12501                getIntentListSubset(
12502                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12503                if (intentListCopy.size() == 0) {
12504                    // no more intents to match; we're not equivalent
12505                    if (DEBUG_FILTERS) {
12506                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12507                                + " package: " + applicationInfo.packageName
12508                                + " activity: " + intent.activity.className
12509                                + " origPrio: " + intent.getPriority());
12510                    }
12511                    intent.setPriority(0);
12512                    return;
12513                }
12514            }
12515
12516            // find matching category subsets
12517            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12518            if (categoriesIterator != null) {
12519                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12520                        categoriesIterator);
12521                if (intentListCopy.size() == 0) {
12522                    // no more intents to match; we're not equivalent
12523                    if (DEBUG_FILTERS) {
12524                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12525                                + " package: " + applicationInfo.packageName
12526                                + " activity: " + intent.activity.className
12527                                + " origPrio: " + intent.getPriority());
12528                    }
12529                    intent.setPriority(0);
12530                    return;
12531                }
12532            }
12533
12534            // find matching schemes subsets
12535            final Iterator<String> schemesIterator = intent.schemesIterator();
12536            if (schemesIterator != null) {
12537                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12538                        schemesIterator);
12539                if (intentListCopy.size() == 0) {
12540                    // no more intents to match; we're not equivalent
12541                    if (DEBUG_FILTERS) {
12542                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12543                                + " package: " + applicationInfo.packageName
12544                                + " activity: " + intent.activity.className
12545                                + " origPrio: " + intent.getPriority());
12546                    }
12547                    intent.setPriority(0);
12548                    return;
12549                }
12550            }
12551
12552            // find matching authorities subsets
12553            final Iterator<IntentFilter.AuthorityEntry>
12554                    authoritiesIterator = intent.authoritiesIterator();
12555            if (authoritiesIterator != null) {
12556                getIntentListSubset(intentListCopy,
12557                        new AuthoritiesIterGenerator(),
12558                        authoritiesIterator);
12559                if (intentListCopy.size() == 0) {
12560                    // no more intents to match; we're not equivalent
12561                    if (DEBUG_FILTERS) {
12562                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12563                                + " package: " + applicationInfo.packageName
12564                                + " activity: " + intent.activity.className
12565                                + " origPrio: " + intent.getPriority());
12566                    }
12567                    intent.setPriority(0);
12568                    return;
12569                }
12570            }
12571
12572            // we found matching filter(s); app gets the max priority of all intents
12573            int cappedPriority = 0;
12574            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12575                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12576            }
12577            if (intent.getPriority() > cappedPriority) {
12578                if (DEBUG_FILTERS) {
12579                    Slog.i(TAG, "Found matching filter(s);"
12580                            + " cap priority to " + cappedPriority + ";"
12581                            + " package: " + applicationInfo.packageName
12582                            + " activity: " + intent.activity.className
12583                            + " origPrio: " + intent.getPriority());
12584                }
12585                intent.setPriority(cappedPriority);
12586                return;
12587            }
12588            // all this for nothing; the requested priority was <= what was on the system
12589        }
12590
12591        public final void addActivity(PackageParser.Activity a, String type) {
12592            mActivities.put(a.getComponentName(), a);
12593            if (DEBUG_SHOW_INFO)
12594                Log.v(
12595                TAG, "  " + type + " " +
12596                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12597            if (DEBUG_SHOW_INFO)
12598                Log.v(TAG, "    Class=" + a.info.name);
12599            final int NI = a.intents.size();
12600            for (int j=0; j<NI; j++) {
12601                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12602                if ("activity".equals(type)) {
12603                    final PackageSetting ps =
12604                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12605                    final List<PackageParser.Activity> systemActivities =
12606                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12607                    adjustPriority(systemActivities, intent);
12608                }
12609                if (DEBUG_SHOW_INFO) {
12610                    Log.v(TAG, "    IntentFilter:");
12611                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12612                }
12613                if (!intent.debugCheck()) {
12614                    Log.w(TAG, "==> For Activity " + a.info.name);
12615                }
12616                addFilter(intent);
12617            }
12618        }
12619
12620        public final void removeActivity(PackageParser.Activity a, String type) {
12621            mActivities.remove(a.getComponentName());
12622            if (DEBUG_SHOW_INFO) {
12623                Log.v(TAG, "  " + type + " "
12624                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12625                                : a.info.name) + ":");
12626                Log.v(TAG, "    Class=" + a.info.name);
12627            }
12628            final int NI = a.intents.size();
12629            for (int j=0; j<NI; j++) {
12630                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12631                if (DEBUG_SHOW_INFO) {
12632                    Log.v(TAG, "    IntentFilter:");
12633                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12634                }
12635                removeFilter(intent);
12636            }
12637        }
12638
12639        @Override
12640        protected boolean allowFilterResult(
12641                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12642            ActivityInfo filterAi = filter.activity.info;
12643            for (int i=dest.size()-1; i>=0; i--) {
12644                ActivityInfo destAi = dest.get(i).activityInfo;
12645                if (destAi.name == filterAi.name
12646                        && destAi.packageName == filterAi.packageName) {
12647                    return false;
12648                }
12649            }
12650            return true;
12651        }
12652
12653        @Override
12654        protected ActivityIntentInfo[] newArray(int size) {
12655            return new ActivityIntentInfo[size];
12656        }
12657
12658        @Override
12659        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12660            if (!sUserManager.exists(userId)) return true;
12661            PackageParser.Package p = filter.activity.owner;
12662            if (p != null) {
12663                PackageSetting ps = (PackageSetting)p.mExtras;
12664                if (ps != null) {
12665                    // System apps are never considered stopped for purposes of
12666                    // filtering, because there may be no way for the user to
12667                    // actually re-launch them.
12668                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12669                            && ps.getStopped(userId);
12670                }
12671            }
12672            return false;
12673        }
12674
12675        @Override
12676        protected boolean isPackageForFilter(String packageName,
12677                PackageParser.ActivityIntentInfo info) {
12678            return packageName.equals(info.activity.owner.packageName);
12679        }
12680
12681        @Override
12682        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12683                int match, int userId) {
12684            if (!sUserManager.exists(userId)) return null;
12685            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12686                return null;
12687            }
12688            final PackageParser.Activity activity = info.activity;
12689            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12690            if (ps == null) {
12691                return null;
12692            }
12693            final PackageUserState userState = ps.readUserState(userId);
12694            ActivityInfo ai =
12695                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
12696            if (ai == null) {
12697                return null;
12698            }
12699            final boolean matchExplicitlyVisibleOnly =
12700                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12701            final boolean matchVisibleToInstantApp =
12702                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12703            final boolean componentVisible =
12704                    matchVisibleToInstantApp
12705                    && info.isVisibleToInstantApp()
12706                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12707            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12708            // throw out filters that aren't visible to ephemeral apps
12709            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12710                return null;
12711            }
12712            // throw out instant app filters if we're not explicitly requesting them
12713            if (!matchInstantApp && userState.instantApp) {
12714                return null;
12715            }
12716            // throw out instant app filters if updates are available; will trigger
12717            // instant app resolution
12718            if (userState.instantApp && ps.isUpdateAvailable()) {
12719                return null;
12720            }
12721            final ResolveInfo res = new ResolveInfo();
12722            res.activityInfo = ai;
12723            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12724                res.filter = info;
12725            }
12726            if (info != null) {
12727                res.handleAllWebDataURI = info.handleAllWebDataURI();
12728            }
12729            res.priority = info.getPriority();
12730            res.preferredOrder = activity.owner.mPreferredOrder;
12731            //System.out.println("Result: " + res.activityInfo.className +
12732            //                   " = " + res.priority);
12733            res.match = match;
12734            res.isDefault = info.hasDefault;
12735            res.labelRes = info.labelRes;
12736            res.nonLocalizedLabel = info.nonLocalizedLabel;
12737            if (userNeedsBadging(userId)) {
12738                res.noResourceId = true;
12739            } else {
12740                res.icon = info.icon;
12741            }
12742            res.iconResourceId = info.icon;
12743            res.system = res.activityInfo.applicationInfo.isSystemApp();
12744            res.isInstantAppAvailable = userState.instantApp;
12745            return res;
12746        }
12747
12748        @Override
12749        protected void sortResults(List<ResolveInfo> results) {
12750            Collections.sort(results, mResolvePrioritySorter);
12751        }
12752
12753        @Override
12754        protected void dumpFilter(PrintWriter out, String prefix,
12755                PackageParser.ActivityIntentInfo filter) {
12756            out.print(prefix); out.print(
12757                    Integer.toHexString(System.identityHashCode(filter.activity)));
12758                    out.print(' ');
12759                    filter.activity.printComponentShortName(out);
12760                    out.print(" filter ");
12761                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12762        }
12763
12764        @Override
12765        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12766            return filter.activity;
12767        }
12768
12769        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12770            PackageParser.Activity activity = (PackageParser.Activity)label;
12771            out.print(prefix); out.print(
12772                    Integer.toHexString(System.identityHashCode(activity)));
12773                    out.print(' ');
12774                    activity.printComponentShortName(out);
12775            if (count > 1) {
12776                out.print(" ("); out.print(count); out.print(" filters)");
12777            }
12778            out.println();
12779        }
12780
12781        // Keys are String (activity class name), values are Activity.
12782        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12783                = new ArrayMap<ComponentName, PackageParser.Activity>();
12784        private int mFlags;
12785    }
12786
12787    private final class ServiceIntentResolver
12788            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12789        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12790                boolean defaultOnly, int userId) {
12791            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12792            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12793        }
12794
12795        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12796                int userId) {
12797            if (!sUserManager.exists(userId)) return null;
12798            mFlags = flags;
12799            return super.queryIntent(intent, resolvedType,
12800                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12801                    userId);
12802        }
12803
12804        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12805                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12806            if (!sUserManager.exists(userId)) return null;
12807            if (packageServices == null) {
12808                return null;
12809            }
12810            mFlags = flags;
12811            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12812            final int N = packageServices.size();
12813            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12814                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12815
12816            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12817            for (int i = 0; i < N; ++i) {
12818                intentFilters = packageServices.get(i).intents;
12819                if (intentFilters != null && intentFilters.size() > 0) {
12820                    PackageParser.ServiceIntentInfo[] array =
12821                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12822                    intentFilters.toArray(array);
12823                    listCut.add(array);
12824                }
12825            }
12826            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12827        }
12828
12829        public final void addService(PackageParser.Service s) {
12830            mServices.put(s.getComponentName(), s);
12831            if (DEBUG_SHOW_INFO) {
12832                Log.v(TAG, "  "
12833                        + (s.info.nonLocalizedLabel != null
12834                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12835                Log.v(TAG, "    Class=" + s.info.name);
12836            }
12837            final int NI = s.intents.size();
12838            int j;
12839            for (j=0; j<NI; j++) {
12840                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12841                if (DEBUG_SHOW_INFO) {
12842                    Log.v(TAG, "    IntentFilter:");
12843                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12844                }
12845                if (!intent.debugCheck()) {
12846                    Log.w(TAG, "==> For Service " + s.info.name);
12847                }
12848                addFilter(intent);
12849            }
12850        }
12851
12852        public final void removeService(PackageParser.Service s) {
12853            mServices.remove(s.getComponentName());
12854            if (DEBUG_SHOW_INFO) {
12855                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12856                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12857                Log.v(TAG, "    Class=" + s.info.name);
12858            }
12859            final int NI = s.intents.size();
12860            int j;
12861            for (j=0; j<NI; j++) {
12862                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12863                if (DEBUG_SHOW_INFO) {
12864                    Log.v(TAG, "    IntentFilter:");
12865                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12866                }
12867                removeFilter(intent);
12868            }
12869        }
12870
12871        @Override
12872        protected boolean allowFilterResult(
12873                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12874            ServiceInfo filterSi = filter.service.info;
12875            for (int i=dest.size()-1; i>=0; i--) {
12876                ServiceInfo destAi = dest.get(i).serviceInfo;
12877                if (destAi.name == filterSi.name
12878                        && destAi.packageName == filterSi.packageName) {
12879                    return false;
12880                }
12881            }
12882            return true;
12883        }
12884
12885        @Override
12886        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12887            return new PackageParser.ServiceIntentInfo[size];
12888        }
12889
12890        @Override
12891        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12892            if (!sUserManager.exists(userId)) return true;
12893            PackageParser.Package p = filter.service.owner;
12894            if (p != null) {
12895                PackageSetting ps = (PackageSetting)p.mExtras;
12896                if (ps != null) {
12897                    // System apps are never considered stopped for purposes of
12898                    // filtering, because there may be no way for the user to
12899                    // actually re-launch them.
12900                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12901                            && ps.getStopped(userId);
12902                }
12903            }
12904            return false;
12905        }
12906
12907        @Override
12908        protected boolean isPackageForFilter(String packageName,
12909                PackageParser.ServiceIntentInfo info) {
12910            return packageName.equals(info.service.owner.packageName);
12911        }
12912
12913        @Override
12914        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12915                int match, int userId) {
12916            if (!sUserManager.exists(userId)) return null;
12917            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12918            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12919                return null;
12920            }
12921            final PackageParser.Service service = info.service;
12922            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12923            if (ps == null) {
12924                return null;
12925            }
12926            final PackageUserState userState = ps.readUserState(userId);
12927            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12928                    userState, userId);
12929            if (si == null) {
12930                return null;
12931            }
12932            final boolean matchVisibleToInstantApp =
12933                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12934            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12935            // throw out filters that aren't visible to ephemeral apps
12936            if (matchVisibleToInstantApp
12937                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12938                return null;
12939            }
12940            // throw out ephemeral filters if we're not explicitly requesting them
12941            if (!isInstantApp && userState.instantApp) {
12942                return null;
12943            }
12944            // throw out instant app filters if updates are available; will trigger
12945            // instant app resolution
12946            if (userState.instantApp && ps.isUpdateAvailable()) {
12947                return null;
12948            }
12949            final ResolveInfo res = new ResolveInfo();
12950            res.serviceInfo = si;
12951            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12952                res.filter = filter;
12953            }
12954            res.priority = info.getPriority();
12955            res.preferredOrder = service.owner.mPreferredOrder;
12956            res.match = match;
12957            res.isDefault = info.hasDefault;
12958            res.labelRes = info.labelRes;
12959            res.nonLocalizedLabel = info.nonLocalizedLabel;
12960            res.icon = info.icon;
12961            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12962            return res;
12963        }
12964
12965        @Override
12966        protected void sortResults(List<ResolveInfo> results) {
12967            Collections.sort(results, mResolvePrioritySorter);
12968        }
12969
12970        @Override
12971        protected void dumpFilter(PrintWriter out, String prefix,
12972                PackageParser.ServiceIntentInfo filter) {
12973            out.print(prefix); out.print(
12974                    Integer.toHexString(System.identityHashCode(filter.service)));
12975                    out.print(' ');
12976                    filter.service.printComponentShortName(out);
12977                    out.print(" filter ");
12978                    out.print(Integer.toHexString(System.identityHashCode(filter)));
12979                    if (filter.service.info.permission != null) {
12980                        out.print(" permission "); out.println(filter.service.info.permission);
12981                    } else {
12982                        out.println();
12983                    }
12984        }
12985
12986        @Override
12987        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12988            return filter.service;
12989        }
12990
12991        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12992            PackageParser.Service service = (PackageParser.Service)label;
12993            out.print(prefix); out.print(
12994                    Integer.toHexString(System.identityHashCode(service)));
12995                    out.print(' ');
12996                    service.printComponentShortName(out);
12997            if (count > 1) {
12998                out.print(" ("); out.print(count); out.print(" filters)");
12999            }
13000            out.println();
13001        }
13002
13003//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13004//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13005//            final List<ResolveInfo> retList = Lists.newArrayList();
13006//            while (i.hasNext()) {
13007//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13008//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13009//                    retList.add(resolveInfo);
13010//                }
13011//            }
13012//            return retList;
13013//        }
13014
13015        // Keys are String (activity class name), values are Activity.
13016        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13017                = new ArrayMap<ComponentName, PackageParser.Service>();
13018        private int mFlags;
13019    }
13020
13021    private final class ProviderIntentResolver
13022            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13023        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13024                boolean defaultOnly, int userId) {
13025            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13026            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13027        }
13028
13029        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13030                int userId) {
13031            if (!sUserManager.exists(userId))
13032                return null;
13033            mFlags = flags;
13034            return super.queryIntent(intent, resolvedType,
13035                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13036                    userId);
13037        }
13038
13039        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13040                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13041            if (!sUserManager.exists(userId))
13042                return null;
13043            if (packageProviders == null) {
13044                return null;
13045            }
13046            mFlags = flags;
13047            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13048            final int N = packageProviders.size();
13049            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13050                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13051
13052            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13053            for (int i = 0; i < N; ++i) {
13054                intentFilters = packageProviders.get(i).intents;
13055                if (intentFilters != null && intentFilters.size() > 0) {
13056                    PackageParser.ProviderIntentInfo[] array =
13057                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13058                    intentFilters.toArray(array);
13059                    listCut.add(array);
13060                }
13061            }
13062            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13063        }
13064
13065        public final void addProvider(PackageParser.Provider p) {
13066            if (mProviders.containsKey(p.getComponentName())) {
13067                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13068                return;
13069            }
13070
13071            mProviders.put(p.getComponentName(), p);
13072            if (DEBUG_SHOW_INFO) {
13073                Log.v(TAG, "  "
13074                        + (p.info.nonLocalizedLabel != null
13075                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13076                Log.v(TAG, "    Class=" + p.info.name);
13077            }
13078            final int NI = p.intents.size();
13079            int j;
13080            for (j = 0; j < NI; j++) {
13081                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13082                if (DEBUG_SHOW_INFO) {
13083                    Log.v(TAG, "    IntentFilter:");
13084                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13085                }
13086                if (!intent.debugCheck()) {
13087                    Log.w(TAG, "==> For Provider " + p.info.name);
13088                }
13089                addFilter(intent);
13090            }
13091        }
13092
13093        public final void removeProvider(PackageParser.Provider p) {
13094            mProviders.remove(p.getComponentName());
13095            if (DEBUG_SHOW_INFO) {
13096                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13097                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13098                Log.v(TAG, "    Class=" + p.info.name);
13099            }
13100            final int NI = p.intents.size();
13101            int j;
13102            for (j = 0; j < NI; j++) {
13103                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13104                if (DEBUG_SHOW_INFO) {
13105                    Log.v(TAG, "    IntentFilter:");
13106                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13107                }
13108                removeFilter(intent);
13109            }
13110        }
13111
13112        @Override
13113        protected boolean allowFilterResult(
13114                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13115            ProviderInfo filterPi = filter.provider.info;
13116            for (int i = dest.size() - 1; i >= 0; i--) {
13117                ProviderInfo destPi = dest.get(i).providerInfo;
13118                if (destPi.name == filterPi.name
13119                        && destPi.packageName == filterPi.packageName) {
13120                    return false;
13121                }
13122            }
13123            return true;
13124        }
13125
13126        @Override
13127        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13128            return new PackageParser.ProviderIntentInfo[size];
13129        }
13130
13131        @Override
13132        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13133            if (!sUserManager.exists(userId))
13134                return true;
13135            PackageParser.Package p = filter.provider.owner;
13136            if (p != null) {
13137                PackageSetting ps = (PackageSetting) p.mExtras;
13138                if (ps != null) {
13139                    // System apps are never considered stopped for purposes of
13140                    // filtering, because there may be no way for the user to
13141                    // actually re-launch them.
13142                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13143                            && ps.getStopped(userId);
13144                }
13145            }
13146            return false;
13147        }
13148
13149        @Override
13150        protected boolean isPackageForFilter(String packageName,
13151                PackageParser.ProviderIntentInfo info) {
13152            return packageName.equals(info.provider.owner.packageName);
13153        }
13154
13155        @Override
13156        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13157                int match, int userId) {
13158            if (!sUserManager.exists(userId))
13159                return null;
13160            final PackageParser.ProviderIntentInfo info = filter;
13161            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13162                return null;
13163            }
13164            final PackageParser.Provider provider = info.provider;
13165            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13166            if (ps == null) {
13167                return null;
13168            }
13169            final PackageUserState userState = ps.readUserState(userId);
13170            final boolean matchVisibleToInstantApp =
13171                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13172            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13173            // throw out filters that aren't visible to instant applications
13174            if (matchVisibleToInstantApp
13175                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13176                return null;
13177            }
13178            // throw out instant application filters if we're not explicitly requesting them
13179            if (!isInstantApp && userState.instantApp) {
13180                return null;
13181            }
13182            // throw out instant application filters if updates are available; will trigger
13183            // instant application resolution
13184            if (userState.instantApp && ps.isUpdateAvailable()) {
13185                return null;
13186            }
13187            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13188                    userState, userId);
13189            if (pi == null) {
13190                return null;
13191            }
13192            final ResolveInfo res = new ResolveInfo();
13193            res.providerInfo = pi;
13194            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13195                res.filter = filter;
13196            }
13197            res.priority = info.getPriority();
13198            res.preferredOrder = provider.owner.mPreferredOrder;
13199            res.match = match;
13200            res.isDefault = info.hasDefault;
13201            res.labelRes = info.labelRes;
13202            res.nonLocalizedLabel = info.nonLocalizedLabel;
13203            res.icon = info.icon;
13204            res.system = res.providerInfo.applicationInfo.isSystemApp();
13205            return res;
13206        }
13207
13208        @Override
13209        protected void sortResults(List<ResolveInfo> results) {
13210            Collections.sort(results, mResolvePrioritySorter);
13211        }
13212
13213        @Override
13214        protected void dumpFilter(PrintWriter out, String prefix,
13215                PackageParser.ProviderIntentInfo filter) {
13216            out.print(prefix);
13217            out.print(
13218                    Integer.toHexString(System.identityHashCode(filter.provider)));
13219            out.print(' ');
13220            filter.provider.printComponentShortName(out);
13221            out.print(" filter ");
13222            out.println(Integer.toHexString(System.identityHashCode(filter)));
13223        }
13224
13225        @Override
13226        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13227            return filter.provider;
13228        }
13229
13230        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13231            PackageParser.Provider provider = (PackageParser.Provider)label;
13232            out.print(prefix); out.print(
13233                    Integer.toHexString(System.identityHashCode(provider)));
13234                    out.print(' ');
13235                    provider.printComponentShortName(out);
13236            if (count > 1) {
13237                out.print(" ("); out.print(count); out.print(" filters)");
13238            }
13239            out.println();
13240        }
13241
13242        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13243                = new ArrayMap<ComponentName, PackageParser.Provider>();
13244        private int mFlags;
13245    }
13246
13247    static final class InstantAppIntentResolver
13248            extends IntentResolver<AuxiliaryResolveInfo.AuxiliaryFilter,
13249            AuxiliaryResolveInfo.AuxiliaryFilter> {
13250        /**
13251         * The result that has the highest defined order. Ordering applies on a
13252         * per-package basis. Mapping is from package name to Pair of order and
13253         * EphemeralResolveInfo.
13254         * <p>
13255         * NOTE: This is implemented as a field variable for convenience and efficiency.
13256         * By having a field variable, we're able to track filter ordering as soon as
13257         * a non-zero order is defined. Otherwise, multiple loops across the result set
13258         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13259         * this needs to be contained entirely within {@link #filterResults}.
13260         */
13261        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13262
13263        @Override
13264        protected AuxiliaryResolveInfo.AuxiliaryFilter[] newArray(int size) {
13265            return new AuxiliaryResolveInfo.AuxiliaryFilter[size];
13266        }
13267
13268        @Override
13269        protected boolean isPackageForFilter(String packageName,
13270                AuxiliaryResolveInfo.AuxiliaryFilter responseObj) {
13271            return true;
13272        }
13273
13274        @Override
13275        protected AuxiliaryResolveInfo.AuxiliaryFilter newResult(
13276                AuxiliaryResolveInfo.AuxiliaryFilter responseObj, int match, int userId) {
13277            if (!sUserManager.exists(userId)) {
13278                return null;
13279            }
13280            final String packageName = responseObj.resolveInfo.getPackageName();
13281            final Integer order = responseObj.getOrder();
13282            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13283                    mOrderResult.get(packageName);
13284            // ordering is enabled and this item's order isn't high enough
13285            if (lastOrderResult != null && lastOrderResult.first >= order) {
13286                return null;
13287            }
13288            final InstantAppResolveInfo res = responseObj.resolveInfo;
13289            if (order > 0) {
13290                // non-zero order, enable ordering
13291                mOrderResult.put(packageName, new Pair<>(order, res));
13292            }
13293            return responseObj;
13294        }
13295
13296        @Override
13297        protected void filterResults(List<AuxiliaryResolveInfo.AuxiliaryFilter> results) {
13298            // only do work if ordering is enabled [most of the time it won't be]
13299            if (mOrderResult.size() == 0) {
13300                return;
13301            }
13302            int resultSize = results.size();
13303            for (int i = 0; i < resultSize; i++) {
13304                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13305                final String packageName = info.getPackageName();
13306                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13307                if (savedInfo == null) {
13308                    // package doesn't having ordering
13309                    continue;
13310                }
13311                if (savedInfo.second == info) {
13312                    // circled back to the highest ordered item; remove from order list
13313                    mOrderResult.remove(packageName);
13314                    if (mOrderResult.size() == 0) {
13315                        // no more ordered items
13316                        break;
13317                    }
13318                    continue;
13319                }
13320                // item has a worse order, remove it from the result list
13321                results.remove(i);
13322                resultSize--;
13323                i--;
13324            }
13325        }
13326    }
13327
13328    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13329            new Comparator<ResolveInfo>() {
13330        public int compare(ResolveInfo r1, ResolveInfo r2) {
13331            int v1 = r1.priority;
13332            int v2 = r2.priority;
13333            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13334            if (v1 != v2) {
13335                return (v1 > v2) ? -1 : 1;
13336            }
13337            v1 = r1.preferredOrder;
13338            v2 = r2.preferredOrder;
13339            if (v1 != v2) {
13340                return (v1 > v2) ? -1 : 1;
13341            }
13342            if (r1.isDefault != r2.isDefault) {
13343                return r1.isDefault ? -1 : 1;
13344            }
13345            v1 = r1.match;
13346            v2 = r2.match;
13347            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13348            if (v1 != v2) {
13349                return (v1 > v2) ? -1 : 1;
13350            }
13351            if (r1.system != r2.system) {
13352                return r1.system ? -1 : 1;
13353            }
13354            if (r1.activityInfo != null) {
13355                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13356            }
13357            if (r1.serviceInfo != null) {
13358                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13359            }
13360            if (r1.providerInfo != null) {
13361                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13362            }
13363            return 0;
13364        }
13365    };
13366
13367    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13368            new Comparator<ProviderInfo>() {
13369        public int compare(ProviderInfo p1, ProviderInfo p2) {
13370            final int v1 = p1.initOrder;
13371            final int v2 = p2.initOrder;
13372            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13373        }
13374    };
13375
13376    @Override
13377    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13378            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13379            final int[] userIds, int[] instantUserIds) {
13380        mHandler.post(new Runnable() {
13381            @Override
13382            public void run() {
13383                try {
13384                    final IActivityManager am = ActivityManager.getService();
13385                    if (am == null) return;
13386                    final int[] resolvedUserIds;
13387                    if (userIds == null) {
13388                        resolvedUserIds = am.getRunningUserIds();
13389                    } else {
13390                        resolvedUserIds = userIds;
13391                    }
13392                    doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13393                            resolvedUserIds, false);
13394                    if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) {
13395                        doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13396                                instantUserIds, true);
13397                    }
13398                } catch (RemoteException ex) {
13399                }
13400            }
13401        });
13402    }
13403
13404    @Override
13405    public void notifyPackageAdded(String packageName) {
13406        final PackageListObserver[] observers;
13407        synchronized (mPackages) {
13408            if (mPackageListObservers.size() == 0) {
13409                return;
13410            }
13411            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13412        }
13413        for (int i = observers.length - 1; i >= 0; --i) {
13414            observers[i].onPackageAdded(packageName);
13415        }
13416    }
13417
13418    @Override
13419    public void notifyPackageRemoved(String packageName) {
13420        final PackageListObserver[] observers;
13421        synchronized (mPackages) {
13422            if (mPackageListObservers.size() == 0) {
13423                return;
13424            }
13425            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13426        }
13427        for (int i = observers.length - 1; i >= 0; --i) {
13428            observers[i].onPackageRemoved(packageName);
13429        }
13430    }
13431
13432    /**
13433     * Sends a broadcast for the given action.
13434     * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with
13435     * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows
13436     * the system and applications allowed to see instant applications to receive package
13437     * lifecycle events for instant applications.
13438     */
13439    private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras,
13440            int flags, String targetPkg, IIntentReceiver finishedReceiver,
13441            int[] userIds, boolean isInstantApp)
13442                    throws RemoteException {
13443        for (int id : userIds) {
13444            final Intent intent = new Intent(action,
13445                    pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13446            final String[] requiredPermissions =
13447                    isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null;
13448            if (extras != null) {
13449                intent.putExtras(extras);
13450            }
13451            if (targetPkg != null) {
13452                intent.setPackage(targetPkg);
13453            }
13454            // Modify the UID when posting to other users
13455            int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13456            if (uid > 0 && UserHandle.getUserId(uid) != id) {
13457                uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13458                intent.putExtra(Intent.EXTRA_UID, uid);
13459            }
13460            intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13461            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13462            if (DEBUG_BROADCASTS) {
13463                RuntimeException here = new RuntimeException("here");
13464                here.fillInStackTrace();
13465                Slog.d(TAG, "Sending to user " + id + ": "
13466                        + intent.toShortString(false, true, false, false)
13467                        + " " + intent.getExtras(), here);
13468            }
13469            am.broadcastIntent(null, intent, null, finishedReceiver,
13470                    0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE,
13471                    null, finishedReceiver != null, false, id);
13472        }
13473    }
13474
13475    /**
13476     * Check if the external storage media is available. This is true if there
13477     * is a mounted external storage medium or if the external storage is
13478     * emulated.
13479     */
13480    private boolean isExternalMediaAvailable() {
13481        return mMediaMounted || Environment.isExternalStorageEmulated();
13482    }
13483
13484    @Override
13485    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13486        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13487            return null;
13488        }
13489        if (!isExternalMediaAvailable()) {
13490                // If the external storage is no longer mounted at this point,
13491                // the caller may not have been able to delete all of this
13492                // packages files and can not delete any more.  Bail.
13493            return null;
13494        }
13495        synchronized (mPackages) {
13496            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13497            if (lastPackage != null) {
13498                pkgs.remove(lastPackage);
13499            }
13500            if (pkgs.size() > 0) {
13501                return pkgs.get(0);
13502            }
13503        }
13504        return null;
13505    }
13506
13507    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13508        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13509                userId, andCode ? 1 : 0, packageName);
13510        if (mSystemReady) {
13511            msg.sendToTarget();
13512        } else {
13513            if (mPostSystemReadyMessages == null) {
13514                mPostSystemReadyMessages = new ArrayList<>();
13515            }
13516            mPostSystemReadyMessages.add(msg);
13517        }
13518    }
13519
13520    void startCleaningPackages() {
13521        // reader
13522        if (!isExternalMediaAvailable()) {
13523            return;
13524        }
13525        synchronized (mPackages) {
13526            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13527                return;
13528            }
13529        }
13530        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13531        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13532        IActivityManager am = ActivityManager.getService();
13533        if (am != null) {
13534            int dcsUid = -1;
13535            synchronized (mPackages) {
13536                if (!mDefaultContainerWhitelisted) {
13537                    mDefaultContainerWhitelisted = true;
13538                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13539                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13540                }
13541            }
13542            try {
13543                if (dcsUid > 0) {
13544                    am.backgroundWhitelistUid(dcsUid);
13545                }
13546                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13547                        UserHandle.USER_SYSTEM);
13548            } catch (RemoteException e) {
13549            }
13550        }
13551    }
13552
13553    /**
13554     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13555     * it is acting on behalf on an enterprise or the user).
13556     *
13557     * Note that the ordering of the conditionals in this method is important. The checks we perform
13558     * are as follows, in this order:
13559     *
13560     * 1) If the install is being performed by a system app, we can trust the app to have set the
13561     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13562     *    what it is.
13563     * 2) If the install is being performed by a device or profile owner app, the install reason
13564     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13565     *    set the install reason correctly. If the app targets an older SDK version where install
13566     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13567     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13568     * 3) In all other cases, the install is being performed by a regular app that is neither part
13569     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13570     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13571     *    set to enterprise policy and if so, change it to unknown instead.
13572     */
13573    private int fixUpInstallReason(String installerPackageName, int installerUid,
13574            int installReason) {
13575        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13576                == PERMISSION_GRANTED) {
13577            // If the install is being performed by a system app, we trust that app to have set the
13578            // install reason correctly.
13579            return installReason;
13580        }
13581
13582        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13583            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13584        if (dpm != null) {
13585            ComponentName owner = null;
13586            try {
13587                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13588                if (owner == null) {
13589                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13590                }
13591            } catch (RemoteException e) {
13592            }
13593            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13594                // If the install is being performed by a device or profile owner, the install
13595                // reason should be enterprise policy.
13596                return PackageManager.INSTALL_REASON_POLICY;
13597            }
13598        }
13599
13600        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13601            // If the install is being performed by a regular app (i.e. neither system app nor
13602            // device or profile owner), we have no reason to believe that the app is acting on
13603            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13604            // change it to unknown instead.
13605            return PackageManager.INSTALL_REASON_UNKNOWN;
13606        }
13607
13608        // If the install is being performed by a regular app and the install reason was set to any
13609        // value but enterprise policy, leave the install reason unchanged.
13610        return installReason;
13611    }
13612
13613    void installStage(String packageName, File stagedDir,
13614            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13615            String installerPackageName, int installerUid, UserHandle user,
13616            PackageParser.SigningDetails signingDetails) {
13617        if (DEBUG_INSTANT) {
13618            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13619                Slog.d(TAG, "Ephemeral install of " + packageName);
13620            }
13621        }
13622        final VerificationInfo verificationInfo = new VerificationInfo(
13623                sessionParams.originatingUri, sessionParams.referrerUri,
13624                sessionParams.originatingUid, installerUid);
13625
13626        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
13627
13628        final Message msg = mHandler.obtainMessage(INIT_COPY);
13629        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13630                sessionParams.installReason);
13631        final InstallParams params = new InstallParams(origin, null, observer,
13632                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13633                verificationInfo, user, sessionParams.abiOverride,
13634                sessionParams.grantedRuntimePermissions, signingDetails, installReason);
13635        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13636        msg.obj = params;
13637
13638        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13639                System.identityHashCode(msg.obj));
13640        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13641                System.identityHashCode(msg.obj));
13642
13643        mHandler.sendMessage(msg);
13644    }
13645
13646    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13647            int userId) {
13648        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13649        final boolean isInstantApp = pkgSetting.getInstantApp(userId);
13650        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
13651        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
13652        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
13653                false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds);
13654
13655        // Send a session commit broadcast
13656        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
13657        info.installReason = pkgSetting.getInstallReason(userId);
13658        info.appPackageName = packageName;
13659        sendSessionCommitBroadcast(info, userId);
13660    }
13661
13662    @Override
13663    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
13664            boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) {
13665        if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) {
13666            return;
13667        }
13668        Bundle extras = new Bundle(1);
13669        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13670        final int uid = UserHandle.getUid(
13671                (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId);
13672        extras.putInt(Intent.EXTRA_UID, uid);
13673
13674        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13675                packageName, extras, 0, null, null, userIds, instantUserIds);
13676        if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) {
13677            mHandler.post(() -> {
13678                        for (int userId : userIds) {
13679                            sendBootCompletedBroadcastToSystemApp(
13680                                    packageName, includeStopped, userId);
13681                        }
13682                    }
13683            );
13684        }
13685    }
13686
13687    /**
13688     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13689     * automatically without needing an explicit launch.
13690     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13691     */
13692    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
13693            int userId) {
13694        // If user is not running, the app didn't miss any broadcast
13695        if (!mUserManagerInternal.isUserRunning(userId)) {
13696            return;
13697        }
13698        final IActivityManager am = ActivityManager.getService();
13699        try {
13700            // Deliver LOCKED_BOOT_COMPLETED first
13701            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13702                    .setPackage(packageName);
13703            if (includeStopped) {
13704                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13705            }
13706            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13707            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13708                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13709
13710            // Deliver BOOT_COMPLETED only if user is unlocked
13711            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13712                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13713                if (includeStopped) {
13714                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13715                }
13716                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13717                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13718            }
13719        } catch (RemoteException e) {
13720            throw e.rethrowFromSystemServer();
13721        }
13722    }
13723
13724    @Override
13725    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13726            int userId) {
13727        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13728        PackageSetting pkgSetting;
13729        final int callingUid = Binder.getCallingUid();
13730        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13731                true /* requireFullPermission */, true /* checkShell */,
13732                "setApplicationHiddenSetting for user " + userId);
13733
13734        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13735            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13736            return false;
13737        }
13738
13739        long callingId = Binder.clearCallingIdentity();
13740        try {
13741            boolean sendAdded = false;
13742            boolean sendRemoved = false;
13743            // writer
13744            synchronized (mPackages) {
13745                pkgSetting = mSettings.mPackages.get(packageName);
13746                if (pkgSetting == null) {
13747                    return false;
13748                }
13749                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13750                    return false;
13751                }
13752                // Do not allow "android" is being disabled
13753                if ("android".equals(packageName)) {
13754                    Slog.w(TAG, "Cannot hide package: android");
13755                    return false;
13756                }
13757                // Cannot hide static shared libs as they are considered
13758                // a part of the using app (emulating static linking). Also
13759                // static libs are installed always on internal storage.
13760                PackageParser.Package pkg = mPackages.get(packageName);
13761                if (pkg != null && pkg.staticSharedLibName != null) {
13762                    Slog.w(TAG, "Cannot hide package: " + packageName
13763                            + " providing static shared library: "
13764                            + pkg.staticSharedLibName);
13765                    return false;
13766                }
13767                // Only allow protected packages to hide themselves.
13768                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
13769                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13770                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13771                    return false;
13772                }
13773
13774                if (pkgSetting.getHidden(userId) != hidden) {
13775                    pkgSetting.setHidden(hidden, userId);
13776                    mSettings.writePackageRestrictionsLPr(userId);
13777                    if (hidden) {
13778                        sendRemoved = true;
13779                    } else {
13780                        sendAdded = true;
13781                    }
13782                }
13783            }
13784            if (sendAdded) {
13785                sendPackageAddedForUser(packageName, pkgSetting, userId);
13786                return true;
13787            }
13788            if (sendRemoved) {
13789                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13790                        "hiding pkg");
13791                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13792                return true;
13793            }
13794        } finally {
13795            Binder.restoreCallingIdentity(callingId);
13796        }
13797        return false;
13798    }
13799
13800    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13801            int userId) {
13802        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13803        info.removedPackage = packageName;
13804        info.installerPackageName = pkgSetting.installerPackageName;
13805        info.removedUsers = new int[] {userId};
13806        info.broadcastUsers = new int[] {userId};
13807        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13808        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13809    }
13810
13811    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13812        if (pkgList.length > 0) {
13813            Bundle extras = new Bundle(1);
13814            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13815
13816            sendPackageBroadcast(
13817                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13818                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13819                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13820                    new int[] {userId}, null);
13821        }
13822    }
13823
13824    /**
13825     * Returns true if application is not found or there was an error. Otherwise it returns
13826     * the hidden state of the package for the given user.
13827     */
13828    @Override
13829    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13830        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13831        final int callingUid = Binder.getCallingUid();
13832        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13833                true /* requireFullPermission */, false /* checkShell */,
13834                "getApplicationHidden for user " + userId);
13835        PackageSetting ps;
13836        long callingId = Binder.clearCallingIdentity();
13837        try {
13838            // writer
13839            synchronized (mPackages) {
13840                ps = mSettings.mPackages.get(packageName);
13841                if (ps == null) {
13842                    return true;
13843                }
13844                if (filterAppAccessLPr(ps, callingUid, userId)) {
13845                    return true;
13846                }
13847                return ps.getHidden(userId);
13848            }
13849        } finally {
13850            Binder.restoreCallingIdentity(callingId);
13851        }
13852    }
13853
13854    /**
13855     * @hide
13856     */
13857    @Override
13858    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13859            int installReason) {
13860        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13861                null);
13862        PackageSetting pkgSetting;
13863        final int callingUid = Binder.getCallingUid();
13864        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13865                true /* requireFullPermission */, true /* checkShell */,
13866                "installExistingPackage for user " + userId);
13867        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13868            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13869        }
13870
13871        long callingId = Binder.clearCallingIdentity();
13872        try {
13873            boolean installed = false;
13874            final boolean instantApp =
13875                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13876            final boolean fullApp =
13877                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13878
13879            // writer
13880            synchronized (mPackages) {
13881                pkgSetting = mSettings.mPackages.get(packageName);
13882                if (pkgSetting == null) {
13883                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13884                }
13885                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
13886                    // only allow the existing package to be used if it's installed as a full
13887                    // application for at least one user
13888                    boolean installAllowed = false;
13889                    for (int checkUserId : sUserManager.getUserIds()) {
13890                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
13891                        if (installAllowed) {
13892                            break;
13893                        }
13894                    }
13895                    if (!installAllowed) {
13896                        return PackageManager.INSTALL_FAILED_INVALID_URI;
13897                    }
13898                }
13899                if (!pkgSetting.getInstalled(userId)) {
13900                    pkgSetting.setInstalled(true, userId);
13901                    pkgSetting.setHidden(false, userId);
13902                    pkgSetting.setInstallReason(installReason, userId);
13903                    mSettings.writePackageRestrictionsLPr(userId);
13904                    mSettings.writeKernelMappingLPr(pkgSetting);
13905                    installed = true;
13906                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13907                    // upgrade app from instant to full; we don't allow app downgrade
13908                    installed = true;
13909                }
13910                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13911            }
13912
13913            if (installed) {
13914                if (pkgSetting.pkg != null) {
13915                    synchronized (mInstallLock) {
13916                        // We don't need to freeze for a brand new install
13917                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13918                    }
13919                }
13920                sendPackageAddedForUser(packageName, pkgSetting, userId);
13921                synchronized (mPackages) {
13922                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
13923                }
13924            }
13925        } finally {
13926            Binder.restoreCallingIdentity(callingId);
13927        }
13928
13929        return PackageManager.INSTALL_SUCCEEDED;
13930    }
13931
13932    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13933            boolean instantApp, boolean fullApp) {
13934        // no state specified; do nothing
13935        if (!instantApp && !fullApp) {
13936            return;
13937        }
13938        if (userId != UserHandle.USER_ALL) {
13939            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13940                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13941            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13942                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13943            }
13944        } else {
13945            for (int currentUserId : sUserManager.getUserIds()) {
13946                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13947                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13948                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13949                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13950                }
13951            }
13952        }
13953    }
13954
13955    boolean isUserRestricted(int userId, String restrictionKey) {
13956        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13957        if (restrictions.getBoolean(restrictionKey, false)) {
13958            Log.w(TAG, "User is restricted: " + restrictionKey);
13959            return true;
13960        }
13961        return false;
13962    }
13963
13964    @Override
13965    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13966            PersistableBundle appExtras, PersistableBundle launcherExtras, String callingPackage,
13967            int userId) {
13968        try {
13969            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.SUSPEND_APPS, null);
13970        } catch (SecurityException e) {
13971            mContext.enforceCallingOrSelfPermission(Manifest.permission.MANAGE_USERS,
13972                    "Callers need to have either " + Manifest.permission.SUSPEND_APPS + " or "
13973                            + Manifest.permission.MANAGE_USERS);
13974        }
13975        final int callingUid = Binder.getCallingUid();
13976        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13977                true /* requireFullPermission */, true /* checkShell */,
13978                "setPackagesSuspended for user " + userId);
13979        if (callingUid != Process.ROOT_UID &&
13980                !UserHandle.isSameApp(getPackageUid(callingPackage, 0, userId), callingUid)) {
13981            throw new IllegalArgumentException("callingPackage " + callingPackage + " does not"
13982                    + " belong to calling app id " + UserHandle.getAppId(callingUid));
13983        }
13984
13985        if (ArrayUtils.isEmpty(packageNames)) {
13986            return packageNames;
13987        }
13988
13989        final List<String> changedPackagesList = new ArrayList<>(packageNames.length);
13990        final List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13991        final long callingId = Binder.clearCallingIdentity();
13992        try {
13993            synchronized (mPackages) {
13994                for (int i = 0; i < packageNames.length; i++) {
13995                    final String packageName = packageNames[i];
13996                    if (callingPackage.equals(packageName)) {
13997                        Slog.w(TAG, "Calling package: " + callingPackage + " trying to "
13998                                + (suspended ? "" : "un") + "suspend itself. Ignoring");
13999                        unactionedPackages.add(packageName);
14000                        continue;
14001                    }
14002                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14003                    if (pkgSetting == null
14004                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14005                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14006                                + "\". Skipping suspending/un-suspending.");
14007                        unactionedPackages.add(packageName);
14008                        continue;
14009                    }
14010                    if (pkgSetting.getSuspended(userId) != suspended) {
14011                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14012                            unactionedPackages.add(packageName);
14013                            continue;
14014                        }
14015                        pkgSetting.setSuspended(suspended, callingPackage, appExtras,
14016                                launcherExtras, userId);
14017                        changedPackagesList.add(packageName);
14018                    }
14019                }
14020            }
14021        } finally {
14022            Binder.restoreCallingIdentity(callingId);
14023        }
14024        if (!changedPackagesList.isEmpty()) {
14025            final String[] changedPackages = changedPackagesList.toArray(
14026                    new String[changedPackagesList.size()]);
14027            sendPackagesSuspendedForUser(changedPackages, userId, suspended);
14028            sendMyPackageSuspendedOrUnsuspended(changedPackages, suspended, appExtras, userId);
14029            synchronized (mPackages) {
14030                scheduleWritePackageRestrictionsLocked(userId);
14031            }
14032        }
14033
14034        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14035    }
14036
14037    @Override
14038    public PersistableBundle getSuspendedPackageAppExtras(String packageName, int userId) {
14039        final int callingUid = Binder.getCallingUid();
14040        if (getPackageUid(packageName, 0, userId) != callingUid) {
14041            mContext.enforceCallingOrSelfPermission(Manifest.permission.SUSPEND_APPS, null);
14042        }
14043        synchronized (mPackages) {
14044            final PackageSetting ps = mSettings.mPackages.get(packageName);
14045            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14046                throw new IllegalArgumentException("Unknown target package: " + packageName);
14047            }
14048            final PackageUserState packageUserState = ps.readUserState(userId);
14049            if (packageUserState.suspended) {
14050                return packageUserState.suspendedAppExtras;
14051            }
14052            return null;
14053        }
14054    }
14055
14056    @Override
14057    public void setSuspendedPackageAppExtras(String packageName, PersistableBundle appExtras,
14058            int userId) {
14059        final int callingUid = Binder.getCallingUid();
14060        mContext.enforceCallingOrSelfPermission(Manifest.permission.SUSPEND_APPS, null);
14061        synchronized (mPackages) {
14062            final PackageSetting ps = mSettings.mPackages.get(packageName);
14063            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14064                throw new IllegalArgumentException("Unknown target package: " + packageName);
14065            }
14066            final PackageUserState packageUserState = ps.readUserState(userId);
14067            if (packageUserState.suspended) {
14068                packageUserState.suspendedAppExtras = appExtras;
14069                sendMyPackageSuspendedOrUnsuspended(new String[] {packageName}, true, appExtras,
14070                        userId);
14071            }
14072        }
14073    }
14074
14075    private void sendMyPackageSuspendedOrUnsuspended(String[] affectedPackages, boolean suspended,
14076            PersistableBundle appExtras, int userId) {
14077        final String action;
14078        final Bundle intentExtras = new Bundle();
14079        if (suspended) {
14080            action = Intent.ACTION_MY_PACKAGE_SUSPENDED;
14081            if (appExtras != null) {
14082                final Bundle bundledAppExtras = new Bundle(appExtras.deepCopy());
14083                intentExtras.putBundle(Intent.EXTRA_SUSPENDED_PACKAGE_EXTRAS, bundledAppExtras);
14084            }
14085        } else {
14086            action = Intent.ACTION_MY_PACKAGE_UNSUSPENDED;
14087        }
14088        mHandler.post(new Runnable() {
14089            @Override
14090            public void run() {
14091                try {
14092                    final IActivityManager am = ActivityManager.getService();
14093                    if (am == null) {
14094                        Slog.wtf(TAG, "IActivityManager null. Cannot send MY_PACKAGE_ "
14095                                + (suspended ? "" : "UN") + "SUSPENDED broadcasts");
14096                        return;
14097                    }
14098                    final int[] targetUserIds = new int[] {userId};
14099                    for (String packageName : affectedPackages) {
14100                        doSendBroadcast(am, action, null, intentExtras,
14101                                Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, packageName, null,
14102                                targetUserIds, false);
14103                    }
14104                } catch (RemoteException ex) {
14105                    // Shouldn't happen as AMS is in the same process.
14106                }
14107            }
14108        });
14109    }
14110
14111    @Override
14112    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14113        final int callingUid = Binder.getCallingUid();
14114        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14115                true /* requireFullPermission */, false /* checkShell */,
14116                "isPackageSuspendedForUser for user " + userId);
14117        if (getPackageUid(packageName, 0, userId) != callingUid) {
14118            mContext.enforceCallingOrSelfPermission(Manifest.permission.SUSPEND_APPS, null);
14119        }
14120        synchronized (mPackages) {
14121            final PackageSetting ps = mSettings.mPackages.get(packageName);
14122            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14123                throw new IllegalArgumentException("Unknown target package: " + packageName);
14124            }
14125            return ps.getSuspended(userId);
14126        }
14127    }
14128
14129    void onSuspendingPackageRemoved(String packageName, int userId) {
14130        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
14131                : new int[] {userId};
14132        synchronized (mPackages) {
14133            for (PackageSetting ps : mSettings.mPackages.values()) {
14134                for (int user : userIds) {
14135                    final PackageUserState pus = ps.readUserState(user);
14136                    if (pus.suspended && packageName.equals(pus.suspendingPackage)) {
14137                        ps.setSuspended(false, null, null, null, user);
14138                    }
14139                }
14140            }
14141        }
14142    }
14143
14144    @GuardedBy("mPackages")
14145    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14146        if (isPackageDeviceAdmin(packageName, userId)) {
14147            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14148                    + "\": has an active device admin");
14149            return false;
14150        }
14151
14152        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14153        if (packageName.equals(activeLauncherPackageName)) {
14154            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14155                    + "\": contains the active launcher");
14156            return false;
14157        }
14158
14159        if (packageName.equals(mRequiredInstallerPackage)) {
14160            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14161                    + "\": required for package installation");
14162            return false;
14163        }
14164
14165        if (packageName.equals(mRequiredUninstallerPackage)) {
14166            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14167                    + "\": required for package uninstallation");
14168            return false;
14169        }
14170
14171        if (packageName.equals(mRequiredVerifierPackage)) {
14172            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14173                    + "\": required for package verification");
14174            return false;
14175        }
14176
14177        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14178            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14179                    + "\": is the default dialer");
14180            return false;
14181        }
14182
14183        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14184            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14185                    + "\": protected package");
14186            return false;
14187        }
14188
14189        // Cannot suspend static shared libs as they are considered
14190        // a part of the using app (emulating static linking). Also
14191        // static libs are installed always on internal storage.
14192        PackageParser.Package pkg = mPackages.get(packageName);
14193        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14194            Slog.w(TAG, "Cannot suspend package: " + packageName
14195                    + " providing static shared library: "
14196                    + pkg.staticSharedLibName);
14197            return false;
14198        }
14199
14200        if (PLATFORM_PACKAGE_NAME.equals(packageName)) {
14201            Slog.w(TAG, "Cannot suspend package: " + packageName);
14202            return false;
14203        }
14204
14205        return true;
14206    }
14207
14208    private String getActiveLauncherPackageName(int userId) {
14209        Intent intent = new Intent(Intent.ACTION_MAIN);
14210        intent.addCategory(Intent.CATEGORY_HOME);
14211        ResolveInfo resolveInfo = resolveIntent(
14212                intent,
14213                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14214                PackageManager.MATCH_DEFAULT_ONLY,
14215                userId);
14216
14217        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14218    }
14219
14220    private String getDefaultDialerPackageName(int userId) {
14221        synchronized (mPackages) {
14222            return mSettings.getDefaultDialerPackageNameLPw(userId);
14223        }
14224    }
14225
14226    @Override
14227    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14228        mContext.enforceCallingOrSelfPermission(
14229                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14230                "Only package verification agents can verify applications");
14231
14232        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14233        final PackageVerificationResponse response = new PackageVerificationResponse(
14234                verificationCode, Binder.getCallingUid());
14235        msg.arg1 = id;
14236        msg.obj = response;
14237        mHandler.sendMessage(msg);
14238    }
14239
14240    @Override
14241    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14242            long millisecondsToDelay) {
14243        mContext.enforceCallingOrSelfPermission(
14244                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14245                "Only package verification agents can extend verification timeouts");
14246
14247        final PackageVerificationState state = mPendingVerification.get(id);
14248        final PackageVerificationResponse response = new PackageVerificationResponse(
14249                verificationCodeAtTimeout, Binder.getCallingUid());
14250
14251        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14252            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14253        }
14254        if (millisecondsToDelay < 0) {
14255            millisecondsToDelay = 0;
14256        }
14257        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14258                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14259            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14260        }
14261
14262        if ((state != null) && !state.timeoutExtended()) {
14263            state.extendTimeout();
14264
14265            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14266            msg.arg1 = id;
14267            msg.obj = response;
14268            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14269        }
14270    }
14271
14272    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14273            int verificationCode, UserHandle user) {
14274        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14275        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14276        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14277        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14278        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14279
14280        mContext.sendBroadcastAsUser(intent, user,
14281                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14282    }
14283
14284    private ComponentName matchComponentForVerifier(String packageName,
14285            List<ResolveInfo> receivers) {
14286        ActivityInfo targetReceiver = null;
14287
14288        final int NR = receivers.size();
14289        for (int i = 0; i < NR; i++) {
14290            final ResolveInfo info = receivers.get(i);
14291            if (info.activityInfo == null) {
14292                continue;
14293            }
14294
14295            if (packageName.equals(info.activityInfo.packageName)) {
14296                targetReceiver = info.activityInfo;
14297                break;
14298            }
14299        }
14300
14301        if (targetReceiver == null) {
14302            return null;
14303        }
14304
14305        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14306    }
14307
14308    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14309            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14310        if (pkgInfo.verifiers.length == 0) {
14311            return null;
14312        }
14313
14314        final int N = pkgInfo.verifiers.length;
14315        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14316        for (int i = 0; i < N; i++) {
14317            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14318
14319            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14320                    receivers);
14321            if (comp == null) {
14322                continue;
14323            }
14324
14325            final int verifierUid = getUidForVerifier(verifierInfo);
14326            if (verifierUid == -1) {
14327                continue;
14328            }
14329
14330            if (DEBUG_VERIFY) {
14331                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14332                        + " with the correct signature");
14333            }
14334            sufficientVerifiers.add(comp);
14335            verificationState.addSufficientVerifier(verifierUid);
14336        }
14337
14338        return sufficientVerifiers;
14339    }
14340
14341    private int getUidForVerifier(VerifierInfo verifierInfo) {
14342        synchronized (mPackages) {
14343            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14344            if (pkg == null) {
14345                return -1;
14346            } else if (pkg.mSigningDetails.signatures.length != 1) {
14347                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14348                        + " has more than one signature; ignoring");
14349                return -1;
14350            }
14351
14352            /*
14353             * If the public key of the package's signature does not match
14354             * our expected public key, then this is a different package and
14355             * we should skip.
14356             */
14357
14358            final byte[] expectedPublicKey;
14359            try {
14360                final Signature verifierSig = pkg.mSigningDetails.signatures[0];
14361                final PublicKey publicKey = verifierSig.getPublicKey();
14362                expectedPublicKey = publicKey.getEncoded();
14363            } catch (CertificateException e) {
14364                return -1;
14365            }
14366
14367            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14368
14369            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14370                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14371                        + " does not have the expected public key; ignoring");
14372                return -1;
14373            }
14374
14375            return pkg.applicationInfo.uid;
14376        }
14377    }
14378
14379    @Override
14380    public void finishPackageInstall(int token, boolean didLaunch) {
14381        enforceSystemOrRoot("Only the system is allowed to finish installs");
14382
14383        if (DEBUG_INSTALL) {
14384            Slog.v(TAG, "BM finishing package install for " + token);
14385        }
14386        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14387
14388        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14389        mHandler.sendMessage(msg);
14390    }
14391
14392    /**
14393     * Get the verification agent timeout.  Used for both the APK verifier and the
14394     * intent filter verifier.
14395     *
14396     * @return verification timeout in milliseconds
14397     */
14398    private long getVerificationTimeout() {
14399        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14400                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14401                DEFAULT_VERIFICATION_TIMEOUT);
14402    }
14403
14404    /**
14405     * Get the default verification agent response code.
14406     *
14407     * @return default verification response code
14408     */
14409    private int getDefaultVerificationResponse(UserHandle user) {
14410        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14411            return PackageManager.VERIFICATION_REJECT;
14412        }
14413        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14414                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14415                DEFAULT_VERIFICATION_RESPONSE);
14416    }
14417
14418    /**
14419     * Check whether or not package verification has been enabled.
14420     *
14421     * @return true if verification should be performed
14422     */
14423    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14424        if (!DEFAULT_VERIFY_ENABLE) {
14425            return false;
14426        }
14427
14428        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14429
14430        // Check if installing from ADB
14431        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14432            // Do not run verification in a test harness environment
14433            if (ActivityManager.isRunningInTestHarness()) {
14434                return false;
14435            }
14436            if (ensureVerifyAppsEnabled) {
14437                return true;
14438            }
14439            // Check if the developer does not want package verification for ADB installs
14440            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14441                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14442                return false;
14443            }
14444        } else {
14445            // only when not installed from ADB, skip verification for instant apps when
14446            // the installer and verifier are the same.
14447            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14448                if (mInstantAppInstallerActivity != null
14449                        && mInstantAppInstallerActivity.packageName.equals(
14450                                mRequiredVerifierPackage)) {
14451                    try {
14452                        mContext.getSystemService(AppOpsManager.class)
14453                                .checkPackage(installerUid, mRequiredVerifierPackage);
14454                        if (DEBUG_VERIFY) {
14455                            Slog.i(TAG, "disable verification for instant app");
14456                        }
14457                        return false;
14458                    } catch (SecurityException ignore) { }
14459                }
14460            }
14461        }
14462
14463        if (ensureVerifyAppsEnabled) {
14464            return true;
14465        }
14466
14467        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14468                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14469    }
14470
14471    @Override
14472    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14473            throws RemoteException {
14474        mContext.enforceCallingOrSelfPermission(
14475                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14476                "Only intentfilter verification agents can verify applications");
14477
14478        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14479        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14480                Binder.getCallingUid(), verificationCode, failedDomains);
14481        msg.arg1 = id;
14482        msg.obj = response;
14483        mHandler.sendMessage(msg);
14484    }
14485
14486    @Override
14487    public int getIntentVerificationStatus(String packageName, int userId) {
14488        final int callingUid = Binder.getCallingUid();
14489        if (UserHandle.getUserId(callingUid) != userId) {
14490            mContext.enforceCallingOrSelfPermission(
14491                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14492                    "getIntentVerificationStatus" + userId);
14493        }
14494        if (getInstantAppPackageName(callingUid) != null) {
14495            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14496        }
14497        synchronized (mPackages) {
14498            final PackageSetting ps = mSettings.mPackages.get(packageName);
14499            if (ps == null
14500                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14501                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14502            }
14503            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14504        }
14505    }
14506
14507    @Override
14508    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14509        mContext.enforceCallingOrSelfPermission(
14510                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14511
14512        boolean result = false;
14513        synchronized (mPackages) {
14514            final PackageSetting ps = mSettings.mPackages.get(packageName);
14515            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14516                return false;
14517            }
14518            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14519        }
14520        if (result) {
14521            scheduleWritePackageRestrictionsLocked(userId);
14522        }
14523        return result;
14524    }
14525
14526    @Override
14527    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14528            String packageName) {
14529        final int callingUid = Binder.getCallingUid();
14530        if (getInstantAppPackageName(callingUid) != null) {
14531            return ParceledListSlice.emptyList();
14532        }
14533        synchronized (mPackages) {
14534            final PackageSetting ps = mSettings.mPackages.get(packageName);
14535            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14536                return ParceledListSlice.emptyList();
14537            }
14538            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14539        }
14540    }
14541
14542    @Override
14543    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14544        if (TextUtils.isEmpty(packageName)) {
14545            return ParceledListSlice.emptyList();
14546        }
14547        final int callingUid = Binder.getCallingUid();
14548        final int callingUserId = UserHandle.getUserId(callingUid);
14549        synchronized (mPackages) {
14550            PackageParser.Package pkg = mPackages.get(packageName);
14551            if (pkg == null || pkg.activities == null) {
14552                return ParceledListSlice.emptyList();
14553            }
14554            if (pkg.mExtras == null) {
14555                return ParceledListSlice.emptyList();
14556            }
14557            final PackageSetting ps = (PackageSetting) pkg.mExtras;
14558            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14559                return ParceledListSlice.emptyList();
14560            }
14561            final int count = pkg.activities.size();
14562            ArrayList<IntentFilter> result = new ArrayList<>();
14563            for (int n=0; n<count; n++) {
14564                PackageParser.Activity activity = pkg.activities.get(n);
14565                if (activity.intents != null && activity.intents.size() > 0) {
14566                    result.addAll(activity.intents);
14567                }
14568            }
14569            return new ParceledListSlice<>(result);
14570        }
14571    }
14572
14573    @Override
14574    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14575        mContext.enforceCallingOrSelfPermission(
14576                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14577        if (UserHandle.getCallingUserId() != userId) {
14578            mContext.enforceCallingOrSelfPermission(
14579                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14580        }
14581
14582        synchronized (mPackages) {
14583            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14584            if (packageName != null) {
14585                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
14586                        packageName, userId);
14587            }
14588            return result;
14589        }
14590    }
14591
14592    @Override
14593    public String getDefaultBrowserPackageName(int userId) {
14594        if (UserHandle.getCallingUserId() != userId) {
14595            mContext.enforceCallingOrSelfPermission(
14596                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14597        }
14598        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14599            return null;
14600        }
14601        synchronized (mPackages) {
14602            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14603        }
14604    }
14605
14606    /**
14607     * Get the "allow unknown sources" setting.
14608     *
14609     * @return the current "allow unknown sources" setting
14610     */
14611    private int getUnknownSourcesSettings() {
14612        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14613                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14614                -1);
14615    }
14616
14617    @Override
14618    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14619        final int callingUid = Binder.getCallingUid();
14620        if (getInstantAppPackageName(callingUid) != null) {
14621            return;
14622        }
14623        // writer
14624        synchronized (mPackages) {
14625            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14626            if (targetPackageSetting == null
14627                    || filterAppAccessLPr(
14628                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
14629                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14630            }
14631
14632            PackageSetting installerPackageSetting;
14633            if (installerPackageName != null) {
14634                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14635                if (installerPackageSetting == null) {
14636                    throw new IllegalArgumentException("Unknown installer package: "
14637                            + installerPackageName);
14638                }
14639            } else {
14640                installerPackageSetting = null;
14641            }
14642
14643            Signature[] callerSignature;
14644            Object obj = mSettings.getUserIdLPr(callingUid);
14645            if (obj != null) {
14646                if (obj instanceof SharedUserSetting) {
14647                    callerSignature =
14648                            ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
14649                } else if (obj instanceof PackageSetting) {
14650                    callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures;
14651                } else {
14652                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
14653                }
14654            } else {
14655                throw new SecurityException("Unknown calling UID: " + callingUid);
14656            }
14657
14658            // Verify: can't set installerPackageName to a package that is
14659            // not signed with the same cert as the caller.
14660            if (installerPackageSetting != null) {
14661                if (compareSignatures(callerSignature,
14662                        installerPackageSetting.signatures.mSigningDetails.signatures)
14663                        != PackageManager.SIGNATURE_MATCH) {
14664                    throw new SecurityException(
14665                            "Caller does not have same cert as new installer package "
14666                            + installerPackageName);
14667                }
14668            }
14669
14670            // Verify: if target already has an installer package, it must
14671            // be signed with the same cert as the caller.
14672            if (targetPackageSetting.installerPackageName != null) {
14673                PackageSetting setting = mSettings.mPackages.get(
14674                        targetPackageSetting.installerPackageName);
14675                // If the currently set package isn't valid, then it's always
14676                // okay to change it.
14677                if (setting != null) {
14678                    if (compareSignatures(callerSignature,
14679                            setting.signatures.mSigningDetails.signatures)
14680                            != PackageManager.SIGNATURE_MATCH) {
14681                        throw new SecurityException(
14682                                "Caller does not have same cert as old installer package "
14683                                + targetPackageSetting.installerPackageName);
14684                    }
14685                }
14686            }
14687
14688            // Okay!
14689            targetPackageSetting.installerPackageName = installerPackageName;
14690            if (installerPackageName != null) {
14691                mSettings.mInstallerPackages.add(installerPackageName);
14692            }
14693            scheduleWriteSettingsLocked();
14694        }
14695    }
14696
14697    @Override
14698    public void setApplicationCategoryHint(String packageName, int categoryHint,
14699            String callerPackageName) {
14700        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14701            throw new SecurityException("Instant applications don't have access to this method");
14702        }
14703        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14704                callerPackageName);
14705        synchronized (mPackages) {
14706            PackageSetting ps = mSettings.mPackages.get(packageName);
14707            if (ps == null) {
14708                throw new IllegalArgumentException("Unknown target package " + packageName);
14709            }
14710            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14711                throw new IllegalArgumentException("Unknown target package " + packageName);
14712            }
14713            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14714                throw new IllegalArgumentException("Calling package " + callerPackageName
14715                        + " is not installer for " + packageName);
14716            }
14717
14718            if (ps.categoryHint != categoryHint) {
14719                ps.categoryHint = categoryHint;
14720                scheduleWriteSettingsLocked();
14721            }
14722        }
14723    }
14724
14725    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14726        // Queue up an async operation since the package installation may take a little while.
14727        mHandler.post(new Runnable() {
14728            public void run() {
14729                mHandler.removeCallbacks(this);
14730                 // Result object to be returned
14731                PackageInstalledInfo res = new PackageInstalledInfo();
14732                res.setReturnCode(currentStatus);
14733                res.uid = -1;
14734                res.pkg = null;
14735                res.removedInfo = null;
14736                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14737                    args.doPreInstall(res.returnCode);
14738                    synchronized (mInstallLock) {
14739                        installPackageTracedLI(args, res);
14740                    }
14741                    args.doPostInstall(res.returnCode, res.uid);
14742                }
14743
14744                // A restore should be performed at this point if (a) the install
14745                // succeeded, (b) the operation is not an update, and (c) the new
14746                // package has not opted out of backup participation.
14747                final boolean update = res.removedInfo != null
14748                        && res.removedInfo.removedPackage != null;
14749                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14750                boolean doRestore = !update
14751                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14752
14753                // Set up the post-install work request bookkeeping.  This will be used
14754                // and cleaned up by the post-install event handling regardless of whether
14755                // there's a restore pass performed.  Token values are >= 1.
14756                int token;
14757                if (mNextInstallToken < 0) mNextInstallToken = 1;
14758                token = mNextInstallToken++;
14759
14760                PostInstallData data = new PostInstallData(args, res);
14761                mRunningInstalls.put(token, data);
14762                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14763
14764                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14765                    // Pass responsibility to the Backup Manager.  It will perform a
14766                    // restore if appropriate, then pass responsibility back to the
14767                    // Package Manager to run the post-install observer callbacks
14768                    // and broadcasts.
14769                    IBackupManager bm = IBackupManager.Stub.asInterface(
14770                            ServiceManager.getService(Context.BACKUP_SERVICE));
14771                    if (bm != null) {
14772                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14773                                + " to BM for possible restore");
14774                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14775                        try {
14776                            // TODO: http://b/22388012
14777                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14778                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14779                            } else {
14780                                doRestore = false;
14781                            }
14782                        } catch (RemoteException e) {
14783                            // can't happen; the backup manager is local
14784                        } catch (Exception e) {
14785                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14786                            doRestore = false;
14787                        }
14788                    } else {
14789                        Slog.e(TAG, "Backup Manager not found!");
14790                        doRestore = false;
14791                    }
14792                }
14793
14794                if (!doRestore) {
14795                    // No restore possible, or the Backup Manager was mysteriously not
14796                    // available -- just fire the post-install work request directly.
14797                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14798
14799                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14800
14801                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14802                    mHandler.sendMessage(msg);
14803                }
14804            }
14805        });
14806    }
14807
14808    /**
14809     * Callback from PackageSettings whenever an app is first transitioned out of the
14810     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14811     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14812     * here whether the app is the target of an ongoing install, and only send the
14813     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14814     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14815     * handling.
14816     */
14817    void notifyFirstLaunch(final String packageName, final String installerPackage,
14818            final int userId) {
14819        // Serialize this with the rest of the install-process message chain.  In the
14820        // restore-at-install case, this Runnable will necessarily run before the
14821        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14822        // are coherent.  In the non-restore case, the app has already completed install
14823        // and been launched through some other means, so it is not in a problematic
14824        // state for observers to see the FIRST_LAUNCH signal.
14825        mHandler.post(new Runnable() {
14826            @Override
14827            public void run() {
14828                for (int i = 0; i < mRunningInstalls.size(); i++) {
14829                    final PostInstallData data = mRunningInstalls.valueAt(i);
14830                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14831                        continue;
14832                    }
14833                    if (packageName.equals(data.res.pkg.applicationInfo.packageName)) {
14834                        // right package; but is it for the right user?
14835                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14836                            if (userId == data.res.newUsers[uIndex]) {
14837                                if (DEBUG_BACKUP) {
14838                                    Slog.i(TAG, "Package " + packageName
14839                                            + " being restored so deferring FIRST_LAUNCH");
14840                                }
14841                                return;
14842                            }
14843                        }
14844                    }
14845                }
14846                // didn't find it, so not being restored
14847                if (DEBUG_BACKUP) {
14848                    Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH");
14849                }
14850                final boolean isInstantApp = isInstantApp(packageName, userId);
14851                final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
14852                final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
14853                sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds);
14854            }
14855        });
14856    }
14857
14858    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg,
14859            int[] userIds, int[] instantUserIds) {
14860        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14861                installerPkg, null, userIds, instantUserIds);
14862    }
14863
14864    private abstract class HandlerParams {
14865        private static final int MAX_RETRIES = 4;
14866
14867        /**
14868         * Number of times startCopy() has been attempted and had a non-fatal
14869         * error.
14870         */
14871        private int mRetries = 0;
14872
14873        /** User handle for the user requesting the information or installation. */
14874        private final UserHandle mUser;
14875        String traceMethod;
14876        int traceCookie;
14877
14878        HandlerParams(UserHandle user) {
14879            mUser = user;
14880        }
14881
14882        UserHandle getUser() {
14883            return mUser;
14884        }
14885
14886        HandlerParams setTraceMethod(String traceMethod) {
14887            this.traceMethod = traceMethod;
14888            return this;
14889        }
14890
14891        HandlerParams setTraceCookie(int traceCookie) {
14892            this.traceCookie = traceCookie;
14893            return this;
14894        }
14895
14896        final boolean startCopy() {
14897            boolean res;
14898            try {
14899                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14900
14901                if (++mRetries > MAX_RETRIES) {
14902                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14903                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14904                    handleServiceError();
14905                    return false;
14906                } else {
14907                    handleStartCopy();
14908                    res = true;
14909                }
14910            } catch (RemoteException e) {
14911                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14912                mHandler.sendEmptyMessage(MCS_RECONNECT);
14913                res = false;
14914            }
14915            handleReturnCode();
14916            return res;
14917        }
14918
14919        final void serviceError() {
14920            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14921            handleServiceError();
14922            handleReturnCode();
14923        }
14924
14925        abstract void handleStartCopy() throws RemoteException;
14926        abstract void handleServiceError();
14927        abstract void handleReturnCode();
14928    }
14929
14930    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14931        for (File path : paths) {
14932            try {
14933                mcs.clearDirectory(path.getAbsolutePath());
14934            } catch (RemoteException e) {
14935            }
14936        }
14937    }
14938
14939    static class OriginInfo {
14940        /**
14941         * Location where install is coming from, before it has been
14942         * copied/renamed into place. This could be a single monolithic APK
14943         * file, or a cluster directory. This location may be untrusted.
14944         */
14945        final File file;
14946
14947        /**
14948         * Flag indicating that {@link #file} or {@link #cid} has already been
14949         * staged, meaning downstream users don't need to defensively copy the
14950         * contents.
14951         */
14952        final boolean staged;
14953
14954        /**
14955         * Flag indicating that {@link #file} or {@link #cid} is an already
14956         * installed app that is being moved.
14957         */
14958        final boolean existing;
14959
14960        final String resolvedPath;
14961        final File resolvedFile;
14962
14963        static OriginInfo fromNothing() {
14964            return new OriginInfo(null, false, false);
14965        }
14966
14967        static OriginInfo fromUntrustedFile(File file) {
14968            return new OriginInfo(file, false, false);
14969        }
14970
14971        static OriginInfo fromExistingFile(File file) {
14972            return new OriginInfo(file, false, true);
14973        }
14974
14975        static OriginInfo fromStagedFile(File file) {
14976            return new OriginInfo(file, true, false);
14977        }
14978
14979        private OriginInfo(File file, boolean staged, boolean existing) {
14980            this.file = file;
14981            this.staged = staged;
14982            this.existing = existing;
14983
14984            if (file != null) {
14985                resolvedPath = file.getAbsolutePath();
14986                resolvedFile = file;
14987            } else {
14988                resolvedPath = null;
14989                resolvedFile = null;
14990            }
14991        }
14992    }
14993
14994    static class MoveInfo {
14995        final int moveId;
14996        final String fromUuid;
14997        final String toUuid;
14998        final String packageName;
14999        final String dataAppName;
15000        final int appId;
15001        final String seinfo;
15002        final int targetSdkVersion;
15003
15004        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15005                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15006            this.moveId = moveId;
15007            this.fromUuid = fromUuid;
15008            this.toUuid = toUuid;
15009            this.packageName = packageName;
15010            this.dataAppName = dataAppName;
15011            this.appId = appId;
15012            this.seinfo = seinfo;
15013            this.targetSdkVersion = targetSdkVersion;
15014        }
15015    }
15016
15017    static class VerificationInfo {
15018        /** A constant used to indicate that a uid value is not present. */
15019        public static final int NO_UID = -1;
15020
15021        /** URI referencing where the package was downloaded from. */
15022        final Uri originatingUri;
15023
15024        /** HTTP referrer URI associated with the originatingURI. */
15025        final Uri referrer;
15026
15027        /** UID of the application that the install request originated from. */
15028        final int originatingUid;
15029
15030        /** UID of application requesting the install */
15031        final int installerUid;
15032
15033        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15034            this.originatingUri = originatingUri;
15035            this.referrer = referrer;
15036            this.originatingUid = originatingUid;
15037            this.installerUid = installerUid;
15038        }
15039    }
15040
15041    class InstallParams extends HandlerParams {
15042        final OriginInfo origin;
15043        final MoveInfo move;
15044        final IPackageInstallObserver2 observer;
15045        int installFlags;
15046        final String installerPackageName;
15047        final String volumeUuid;
15048        private InstallArgs mArgs;
15049        private int mRet;
15050        final String packageAbiOverride;
15051        final String[] grantedRuntimePermissions;
15052        final VerificationInfo verificationInfo;
15053        final PackageParser.SigningDetails signingDetails;
15054        final int installReason;
15055
15056        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15057                int installFlags, String installerPackageName, String volumeUuid,
15058                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15059                String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) {
15060            super(user);
15061            this.origin = origin;
15062            this.move = move;
15063            this.observer = observer;
15064            this.installFlags = installFlags;
15065            this.installerPackageName = installerPackageName;
15066            this.volumeUuid = volumeUuid;
15067            this.verificationInfo = verificationInfo;
15068            this.packageAbiOverride = packageAbiOverride;
15069            this.grantedRuntimePermissions = grantedPermissions;
15070            this.signingDetails = signingDetails;
15071            this.installReason = installReason;
15072        }
15073
15074        @Override
15075        public String toString() {
15076            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15077                    + " file=" + origin.file + "}";
15078        }
15079
15080        private int installLocationPolicy(PackageInfoLite pkgLite) {
15081            String packageName = pkgLite.packageName;
15082            int installLocation = pkgLite.installLocation;
15083            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15084            // reader
15085            synchronized (mPackages) {
15086                // Currently installed package which the new package is attempting to replace or
15087                // null if no such package is installed.
15088                PackageParser.Package installedPkg = mPackages.get(packageName);
15089                // Package which currently owns the data which the new package will own if installed.
15090                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15091                // will be null whereas dataOwnerPkg will contain information about the package
15092                // which was uninstalled while keeping its data.
15093                PackageParser.Package dataOwnerPkg = installedPkg;
15094                if (dataOwnerPkg  == null) {
15095                    PackageSetting ps = mSettings.mPackages.get(packageName);
15096                    if (ps != null) {
15097                        dataOwnerPkg = ps.pkg;
15098                    }
15099                }
15100
15101                if (dataOwnerPkg != null) {
15102                    // If installed, the package will get access to data left on the device by its
15103                    // predecessor. As a security measure, this is permited only if this is not a
15104                    // version downgrade or if the predecessor package is marked as debuggable and
15105                    // a downgrade is explicitly requested.
15106                    //
15107                    // On debuggable platform builds, downgrades are permitted even for
15108                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15109                    // not offer security guarantees and thus it's OK to disable some security
15110                    // mechanisms to make debugging/testing easier on those builds. However, even on
15111                    // debuggable builds downgrades of packages are permitted only if requested via
15112                    // installFlags. This is because we aim to keep the behavior of debuggable
15113                    // platform builds as close as possible to the behavior of non-debuggable
15114                    // platform builds.
15115                    final boolean downgradeRequested =
15116                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15117                    final boolean packageDebuggable =
15118                                (dataOwnerPkg.applicationInfo.flags
15119                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15120                    final boolean downgradePermitted =
15121                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15122                    if (!downgradePermitted) {
15123                        try {
15124                            checkDowngrade(dataOwnerPkg, pkgLite);
15125                        } catch (PackageManagerException e) {
15126                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15127                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15128                        }
15129                    }
15130                }
15131
15132                if (installedPkg != null) {
15133                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15134                        // Check for updated system application.
15135                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15136                            if (onSd) {
15137                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15138                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15139                            }
15140                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15141                        } else {
15142                            if (onSd) {
15143                                // Install flag overrides everything.
15144                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15145                            }
15146                            // If current upgrade specifies particular preference
15147                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15148                                // Application explicitly specified internal.
15149                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15150                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15151                                // App explictly prefers external. Let policy decide
15152                            } else {
15153                                // Prefer previous location
15154                                if (isExternal(installedPkg)) {
15155                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15156                                }
15157                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15158                            }
15159                        }
15160                    } else {
15161                        // Invalid install. Return error code
15162                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15163                    }
15164                }
15165            }
15166            // All the special cases have been taken care of.
15167            // Return result based on recommended install location.
15168            if (onSd) {
15169                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15170            }
15171            return pkgLite.recommendedInstallLocation;
15172        }
15173
15174        /*
15175         * Invoke remote method to get package information and install
15176         * location values. Override install location based on default
15177         * policy if needed and then create install arguments based
15178         * on the install location.
15179         */
15180        public void handleStartCopy() throws RemoteException {
15181            int ret = PackageManager.INSTALL_SUCCEEDED;
15182
15183            // If we're already staged, we've firmly committed to an install location
15184            if (origin.staged) {
15185                if (origin.file != null) {
15186                    installFlags |= PackageManager.INSTALL_INTERNAL;
15187                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15188                } else {
15189                    throw new IllegalStateException("Invalid stage location");
15190                }
15191            }
15192
15193            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15194            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15195            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15196            PackageInfoLite pkgLite = null;
15197
15198            if (onInt && onSd) {
15199                // Check if both bits are set.
15200                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15201                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15202            } else if (onSd && ephemeral) {
15203                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15204                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15205            } else {
15206                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15207                        packageAbiOverride);
15208
15209                if (DEBUG_INSTANT && ephemeral) {
15210                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15211                }
15212
15213                /*
15214                 * If we have too little free space, try to free cache
15215                 * before giving up.
15216                 */
15217                if (!origin.staged && pkgLite.recommendedInstallLocation
15218                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15219                    // TODO: focus freeing disk space on the target device
15220                    final StorageManager storage = StorageManager.from(mContext);
15221                    final long lowThreshold = storage.getStorageLowBytes(
15222                            Environment.getDataDirectory());
15223
15224                    final long sizeBytes = mContainerService.calculateInstalledSize(
15225                            origin.resolvedPath, packageAbiOverride);
15226
15227                    try {
15228                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15229                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15230                                installFlags, packageAbiOverride);
15231                    } catch (InstallerException e) {
15232                        Slog.w(TAG, "Failed to free cache", e);
15233                    }
15234
15235                    /*
15236                     * The cache free must have deleted the file we
15237                     * downloaded to install.
15238                     *
15239                     * TODO: fix the "freeCache" call to not delete
15240                     *       the file we care about.
15241                     */
15242                    if (pkgLite.recommendedInstallLocation
15243                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15244                        pkgLite.recommendedInstallLocation
15245                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15246                    }
15247                }
15248            }
15249
15250            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15251                int loc = pkgLite.recommendedInstallLocation;
15252                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15253                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15254                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15255                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15256                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15257                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15258                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15259                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15260                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15261                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15262                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15263                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15264                } else {
15265                    // Override with defaults if needed.
15266                    loc = installLocationPolicy(pkgLite);
15267                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15268                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15269                    } else if (!onSd && !onInt) {
15270                        // Override install location with flags
15271                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15272                            // Set the flag to install on external media.
15273                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15274                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15275                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15276                            if (DEBUG_INSTANT) {
15277                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15278                            }
15279                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15280                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15281                                    |PackageManager.INSTALL_INTERNAL);
15282                        } else {
15283                            // Make sure the flag for installing on external
15284                            // media is unset
15285                            installFlags |= PackageManager.INSTALL_INTERNAL;
15286                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15287                        }
15288                    }
15289                }
15290            }
15291
15292            final InstallArgs args = createInstallArgs(this);
15293            mArgs = args;
15294
15295            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15296                // TODO: http://b/22976637
15297                // Apps installed for "all" users use the device owner to verify the app
15298                UserHandle verifierUser = getUser();
15299                if (verifierUser == UserHandle.ALL) {
15300                    verifierUser = UserHandle.SYSTEM;
15301                }
15302
15303                /*
15304                 * Determine if we have any installed package verifiers. If we
15305                 * do, then we'll defer to them to verify the packages.
15306                 */
15307                final int requiredUid = mRequiredVerifierPackage == null ? -1
15308                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15309                                verifierUser.getIdentifier());
15310                final int installerUid =
15311                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15312                if (!origin.existing && requiredUid != -1
15313                        && isVerificationEnabled(
15314                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15315                    final Intent verification = new Intent(
15316                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15317                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15318                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15319                            PACKAGE_MIME_TYPE);
15320                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15321
15322                    // Query all live verifiers based on current user state
15323                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15324                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
15325                            false /*allowDynamicSplits*/);
15326
15327                    if (DEBUG_VERIFY) {
15328                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15329                                + verification.toString() + " with " + pkgLite.verifiers.length
15330                                + " optional verifiers");
15331                    }
15332
15333                    final int verificationId = mPendingVerificationToken++;
15334
15335                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15336
15337                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15338                            installerPackageName);
15339
15340                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15341                            installFlags);
15342
15343                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15344                            pkgLite.packageName);
15345
15346                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15347                            pkgLite.versionCode);
15348
15349                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE,
15350                            pkgLite.getLongVersionCode());
15351
15352                    if (verificationInfo != null) {
15353                        if (verificationInfo.originatingUri != null) {
15354                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15355                                    verificationInfo.originatingUri);
15356                        }
15357                        if (verificationInfo.referrer != null) {
15358                            verification.putExtra(Intent.EXTRA_REFERRER,
15359                                    verificationInfo.referrer);
15360                        }
15361                        if (verificationInfo.originatingUid >= 0) {
15362                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15363                                    verificationInfo.originatingUid);
15364                        }
15365                        if (verificationInfo.installerUid >= 0) {
15366                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15367                                    verificationInfo.installerUid);
15368                        }
15369                    }
15370
15371                    final PackageVerificationState verificationState = new PackageVerificationState(
15372                            requiredUid, args);
15373
15374                    mPendingVerification.append(verificationId, verificationState);
15375
15376                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15377                            receivers, verificationState);
15378
15379                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15380                    final long idleDuration = getVerificationTimeout();
15381
15382                    /*
15383                     * If any sufficient verifiers were listed in the package
15384                     * manifest, attempt to ask them.
15385                     */
15386                    if (sufficientVerifiers != null) {
15387                        final int N = sufficientVerifiers.size();
15388                        if (N == 0) {
15389                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15390                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15391                        } else {
15392                            for (int i = 0; i < N; i++) {
15393                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15394                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15395                                        verifierComponent.getPackageName(), idleDuration,
15396                                        verifierUser.getIdentifier(), false, "package verifier");
15397
15398                                final Intent sufficientIntent = new Intent(verification);
15399                                sufficientIntent.setComponent(verifierComponent);
15400                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15401                            }
15402                        }
15403                    }
15404
15405                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15406                            mRequiredVerifierPackage, receivers);
15407                    if (ret == PackageManager.INSTALL_SUCCEEDED
15408                            && mRequiredVerifierPackage != null) {
15409                        Trace.asyncTraceBegin(
15410                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15411                        /*
15412                         * Send the intent to the required verification agent,
15413                         * but only start the verification timeout after the
15414                         * target BroadcastReceivers have run.
15415                         */
15416                        verification.setComponent(requiredVerifierComponent);
15417                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15418                                mRequiredVerifierPackage, idleDuration,
15419                                verifierUser.getIdentifier(), false, "package verifier");
15420                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15421                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15422                                new BroadcastReceiver() {
15423                                    @Override
15424                                    public void onReceive(Context context, Intent intent) {
15425                                        final Message msg = mHandler
15426                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15427                                        msg.arg1 = verificationId;
15428                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15429                                    }
15430                                }, null, 0, null, null);
15431
15432                        /*
15433                         * We don't want the copy to proceed until verification
15434                         * succeeds, so null out this field.
15435                         */
15436                        mArgs = null;
15437                    }
15438                } else {
15439                    /*
15440                     * No package verification is enabled, so immediately start
15441                     * the remote call to initiate copy using temporary file.
15442                     */
15443                    ret = args.copyApk(mContainerService, true);
15444                }
15445            }
15446
15447            mRet = ret;
15448        }
15449
15450        @Override
15451        void handleReturnCode() {
15452            // If mArgs is null, then MCS couldn't be reached. When it
15453            // reconnects, it will try again to install. At that point, this
15454            // will succeed.
15455            if (mArgs != null) {
15456                processPendingInstall(mArgs, mRet);
15457            }
15458        }
15459
15460        @Override
15461        void handleServiceError() {
15462            mArgs = createInstallArgs(this);
15463            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15464        }
15465    }
15466
15467    private InstallArgs createInstallArgs(InstallParams params) {
15468        if (params.move != null) {
15469            return new MoveInstallArgs(params);
15470        } else {
15471            return new FileInstallArgs(params);
15472        }
15473    }
15474
15475    /**
15476     * Create args that describe an existing installed package. Typically used
15477     * when cleaning up old installs, or used as a move source.
15478     */
15479    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15480            String resourcePath, String[] instructionSets) {
15481        return new FileInstallArgs(codePath, resourcePath, instructionSets);
15482    }
15483
15484    static abstract class InstallArgs {
15485        /** @see InstallParams#origin */
15486        final OriginInfo origin;
15487        /** @see InstallParams#move */
15488        final MoveInfo move;
15489
15490        final IPackageInstallObserver2 observer;
15491        // Always refers to PackageManager flags only
15492        final int installFlags;
15493        final String installerPackageName;
15494        final String volumeUuid;
15495        final UserHandle user;
15496        final String abiOverride;
15497        final String[] installGrantPermissions;
15498        /** If non-null, drop an async trace when the install completes */
15499        final String traceMethod;
15500        final int traceCookie;
15501        final PackageParser.SigningDetails signingDetails;
15502        final int installReason;
15503
15504        // The list of instruction sets supported by this app. This is currently
15505        // only used during the rmdex() phase to clean up resources. We can get rid of this
15506        // if we move dex files under the common app path.
15507        /* nullable */ String[] instructionSets;
15508
15509        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15510                int installFlags, String installerPackageName, String volumeUuid,
15511                UserHandle user, String[] instructionSets,
15512                String abiOverride, String[] installGrantPermissions,
15513                String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails,
15514                int installReason) {
15515            this.origin = origin;
15516            this.move = move;
15517            this.installFlags = installFlags;
15518            this.observer = observer;
15519            this.installerPackageName = installerPackageName;
15520            this.volumeUuid = volumeUuid;
15521            this.user = user;
15522            this.instructionSets = instructionSets;
15523            this.abiOverride = abiOverride;
15524            this.installGrantPermissions = installGrantPermissions;
15525            this.traceMethod = traceMethod;
15526            this.traceCookie = traceCookie;
15527            this.signingDetails = signingDetails;
15528            this.installReason = installReason;
15529        }
15530
15531        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15532        abstract int doPreInstall(int status);
15533
15534        /**
15535         * Rename package into final resting place. All paths on the given
15536         * scanned package should be updated to reflect the rename.
15537         */
15538        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15539        abstract int doPostInstall(int status, int uid);
15540
15541        /** @see PackageSettingBase#codePathString */
15542        abstract String getCodePath();
15543        /** @see PackageSettingBase#resourcePathString */
15544        abstract String getResourcePath();
15545
15546        // Need installer lock especially for dex file removal.
15547        abstract void cleanUpResourcesLI();
15548        abstract boolean doPostDeleteLI(boolean delete);
15549
15550        /**
15551         * Called before the source arguments are copied. This is used mostly
15552         * for MoveParams when it needs to read the source file to put it in the
15553         * destination.
15554         */
15555        int doPreCopy() {
15556            return PackageManager.INSTALL_SUCCEEDED;
15557        }
15558
15559        /**
15560         * Called after the source arguments are copied. This is used mostly for
15561         * MoveParams when it needs to read the source file to put it in the
15562         * destination.
15563         */
15564        int doPostCopy(int uid) {
15565            return PackageManager.INSTALL_SUCCEEDED;
15566        }
15567
15568        protected boolean isFwdLocked() {
15569            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15570        }
15571
15572        protected boolean isExternalAsec() {
15573            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15574        }
15575
15576        protected boolean isEphemeral() {
15577            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15578        }
15579
15580        UserHandle getUser() {
15581            return user;
15582        }
15583    }
15584
15585    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15586        if (!allCodePaths.isEmpty()) {
15587            if (instructionSets == null) {
15588                throw new IllegalStateException("instructionSet == null");
15589            }
15590            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15591            for (String codePath : allCodePaths) {
15592                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15593                    try {
15594                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15595                    } catch (InstallerException ignored) {
15596                    }
15597                }
15598            }
15599        }
15600    }
15601
15602    /**
15603     * Logic to handle installation of non-ASEC applications, including copying
15604     * and renaming logic.
15605     */
15606    class FileInstallArgs extends InstallArgs {
15607        private File codeFile;
15608        private File resourceFile;
15609
15610        // Example topology:
15611        // /data/app/com.example/base.apk
15612        // /data/app/com.example/split_foo.apk
15613        // /data/app/com.example/lib/arm/libfoo.so
15614        // /data/app/com.example/lib/arm64/libfoo.so
15615        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15616
15617        /** New install */
15618        FileInstallArgs(InstallParams params) {
15619            super(params.origin, params.move, params.observer, params.installFlags,
15620                    params.installerPackageName, params.volumeUuid,
15621                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15622                    params.grantedRuntimePermissions,
15623                    params.traceMethod, params.traceCookie, params.signingDetails,
15624                    params.installReason);
15625            if (isFwdLocked()) {
15626                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15627            }
15628        }
15629
15630        /** Existing install */
15631        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15632            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15633                    null, null, null, 0, PackageParser.SigningDetails.UNKNOWN,
15634                    PackageManager.INSTALL_REASON_UNKNOWN);
15635            this.codeFile = (codePath != null) ? new File(codePath) : null;
15636            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15637        }
15638
15639        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15640            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15641            try {
15642                return doCopyApk(imcs, temp);
15643            } finally {
15644                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15645            }
15646        }
15647
15648        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15649            if (origin.staged) {
15650                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15651                codeFile = origin.file;
15652                resourceFile = origin.file;
15653                return PackageManager.INSTALL_SUCCEEDED;
15654            }
15655
15656            try {
15657                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15658                final File tempDir =
15659                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15660                codeFile = tempDir;
15661                resourceFile = tempDir;
15662            } catch (IOException e) {
15663                Slog.w(TAG, "Failed to create copy file: " + e);
15664                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15665            }
15666
15667            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15668                @Override
15669                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15670                    if (!FileUtils.isValidExtFilename(name)) {
15671                        throw new IllegalArgumentException("Invalid filename: " + name);
15672                    }
15673                    try {
15674                        final File file = new File(codeFile, name);
15675                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15676                                O_RDWR | O_CREAT, 0644);
15677                        Os.chmod(file.getAbsolutePath(), 0644);
15678                        return new ParcelFileDescriptor(fd);
15679                    } catch (ErrnoException e) {
15680                        throw new RemoteException("Failed to open: " + e.getMessage());
15681                    }
15682                }
15683            };
15684
15685            int ret = PackageManager.INSTALL_SUCCEEDED;
15686            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15687            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15688                Slog.e(TAG, "Failed to copy package");
15689                return ret;
15690            }
15691
15692            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15693            NativeLibraryHelper.Handle handle = null;
15694            try {
15695                handle = NativeLibraryHelper.Handle.create(codeFile);
15696                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15697                        abiOverride);
15698            } catch (IOException e) {
15699                Slog.e(TAG, "Copying native libraries failed", e);
15700                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15701            } finally {
15702                IoUtils.closeQuietly(handle);
15703            }
15704
15705            return ret;
15706        }
15707
15708        int doPreInstall(int status) {
15709            if (status != PackageManager.INSTALL_SUCCEEDED) {
15710                cleanUp();
15711            }
15712            return status;
15713        }
15714
15715        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15716            if (status != PackageManager.INSTALL_SUCCEEDED) {
15717                cleanUp();
15718                return false;
15719            }
15720
15721            final File targetDir = codeFile.getParentFile();
15722            final File beforeCodeFile = codeFile;
15723            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15724
15725            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15726            try {
15727                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15728            } catch (ErrnoException e) {
15729                Slog.w(TAG, "Failed to rename", e);
15730                return false;
15731            }
15732
15733            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15734                Slog.w(TAG, "Failed to restorecon");
15735                return false;
15736            }
15737
15738            // Reflect the rename internally
15739            codeFile = afterCodeFile;
15740            resourceFile = afterCodeFile;
15741
15742            // Reflect the rename in scanned details
15743            try {
15744                pkg.setCodePath(afterCodeFile.getCanonicalPath());
15745            } catch (IOException e) {
15746                Slog.e(TAG, "Failed to get path: " + afterCodeFile, e);
15747                return false;
15748            }
15749            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15750                    afterCodeFile, pkg.baseCodePath));
15751            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15752                    afterCodeFile, pkg.splitCodePaths));
15753
15754            // Reflect the rename in app info
15755            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15756            pkg.setApplicationInfoCodePath(pkg.codePath);
15757            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15758            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15759            pkg.setApplicationInfoResourcePath(pkg.codePath);
15760            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15761            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15762
15763            return true;
15764        }
15765
15766        int doPostInstall(int status, int uid) {
15767            if (status != PackageManager.INSTALL_SUCCEEDED) {
15768                cleanUp();
15769            }
15770            return status;
15771        }
15772
15773        @Override
15774        String getCodePath() {
15775            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15776        }
15777
15778        @Override
15779        String getResourcePath() {
15780            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15781        }
15782
15783        private boolean cleanUp() {
15784            if (codeFile == null || !codeFile.exists()) {
15785                return false;
15786            }
15787
15788            removeCodePathLI(codeFile);
15789
15790            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15791                resourceFile.delete();
15792            }
15793
15794            return true;
15795        }
15796
15797        void cleanUpResourcesLI() {
15798            // Try enumerating all code paths before deleting
15799            List<String> allCodePaths = Collections.EMPTY_LIST;
15800            if (codeFile != null && codeFile.exists()) {
15801                try {
15802                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15803                    allCodePaths = pkg.getAllCodePaths();
15804                } catch (PackageParserException e) {
15805                    // Ignored; we tried our best
15806                }
15807            }
15808
15809            cleanUp();
15810            removeDexFiles(allCodePaths, instructionSets);
15811        }
15812
15813        boolean doPostDeleteLI(boolean delete) {
15814            // XXX err, shouldn't we respect the delete flag?
15815            cleanUpResourcesLI();
15816            return true;
15817        }
15818    }
15819
15820    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15821            PackageManagerException {
15822        if (copyRet < 0) {
15823            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15824                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15825                throw new PackageManagerException(copyRet, message);
15826            }
15827        }
15828    }
15829
15830    /**
15831     * Extract the StorageManagerService "container ID" from the full code path of an
15832     * .apk.
15833     */
15834    static String cidFromCodePath(String fullCodePath) {
15835        int eidx = fullCodePath.lastIndexOf("/");
15836        String subStr1 = fullCodePath.substring(0, eidx);
15837        int sidx = subStr1.lastIndexOf("/");
15838        return subStr1.substring(sidx+1, eidx);
15839    }
15840
15841    /**
15842     * Logic to handle movement of existing installed applications.
15843     */
15844    class MoveInstallArgs extends InstallArgs {
15845        private File codeFile;
15846        private File resourceFile;
15847
15848        /** New install */
15849        MoveInstallArgs(InstallParams params) {
15850            super(params.origin, params.move, params.observer, params.installFlags,
15851                    params.installerPackageName, params.volumeUuid,
15852                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15853                    params.grantedRuntimePermissions,
15854                    params.traceMethod, params.traceCookie, params.signingDetails,
15855                    params.installReason);
15856        }
15857
15858        int copyApk(IMediaContainerService imcs, boolean temp) {
15859            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15860                    + move.fromUuid + " to " + move.toUuid);
15861            synchronized (mInstaller) {
15862                try {
15863                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15864                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15865                } catch (InstallerException e) {
15866                    Slog.w(TAG, "Failed to move app", e);
15867                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15868                }
15869            }
15870
15871            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15872            resourceFile = codeFile;
15873            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15874
15875            return PackageManager.INSTALL_SUCCEEDED;
15876        }
15877
15878        int doPreInstall(int status) {
15879            if (status != PackageManager.INSTALL_SUCCEEDED) {
15880                cleanUp(move.toUuid);
15881            }
15882            return status;
15883        }
15884
15885        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15886            if (status != PackageManager.INSTALL_SUCCEEDED) {
15887                cleanUp(move.toUuid);
15888                return false;
15889            }
15890
15891            // Reflect the move in app info
15892            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15893            pkg.setApplicationInfoCodePath(pkg.codePath);
15894            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15895            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15896            pkg.setApplicationInfoResourcePath(pkg.codePath);
15897            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15898            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15899
15900            return true;
15901        }
15902
15903        int doPostInstall(int status, int uid) {
15904            if (status == PackageManager.INSTALL_SUCCEEDED) {
15905                cleanUp(move.fromUuid);
15906            } else {
15907                cleanUp(move.toUuid);
15908            }
15909            return status;
15910        }
15911
15912        @Override
15913        String getCodePath() {
15914            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15915        }
15916
15917        @Override
15918        String getResourcePath() {
15919            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15920        }
15921
15922        private boolean cleanUp(String volumeUuid) {
15923            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15924                    move.dataAppName);
15925            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15926            final int[] userIds = sUserManager.getUserIds();
15927            synchronized (mInstallLock) {
15928                // Clean up both app data and code
15929                // All package moves are frozen until finished
15930                for (int userId : userIds) {
15931                    try {
15932                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15933                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15934                    } catch (InstallerException e) {
15935                        Slog.w(TAG, String.valueOf(e));
15936                    }
15937                }
15938                removeCodePathLI(codeFile);
15939            }
15940            return true;
15941        }
15942
15943        void cleanUpResourcesLI() {
15944            throw new UnsupportedOperationException();
15945        }
15946
15947        boolean doPostDeleteLI(boolean delete) {
15948            throw new UnsupportedOperationException();
15949        }
15950    }
15951
15952    static String getAsecPackageName(String packageCid) {
15953        int idx = packageCid.lastIndexOf("-");
15954        if (idx == -1) {
15955            return packageCid;
15956        }
15957        return packageCid.substring(0, idx);
15958    }
15959
15960    // Utility method used to create code paths based on package name and available index.
15961    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15962        String idxStr = "";
15963        int idx = 1;
15964        // Fall back to default value of idx=1 if prefix is not
15965        // part of oldCodePath
15966        if (oldCodePath != null) {
15967            String subStr = oldCodePath;
15968            // Drop the suffix right away
15969            if (suffix != null && subStr.endsWith(suffix)) {
15970                subStr = subStr.substring(0, subStr.length() - suffix.length());
15971            }
15972            // If oldCodePath already contains prefix find out the
15973            // ending index to either increment or decrement.
15974            int sidx = subStr.lastIndexOf(prefix);
15975            if (sidx != -1) {
15976                subStr = subStr.substring(sidx + prefix.length());
15977                if (subStr != null) {
15978                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15979                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15980                    }
15981                    try {
15982                        idx = Integer.parseInt(subStr);
15983                        if (idx <= 1) {
15984                            idx++;
15985                        } else {
15986                            idx--;
15987                        }
15988                    } catch(NumberFormatException e) {
15989                    }
15990                }
15991            }
15992        }
15993        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15994        return prefix + idxStr;
15995    }
15996
15997    private File getNextCodePath(File targetDir, String packageName) {
15998        File result;
15999        SecureRandom random = new SecureRandom();
16000        byte[] bytes = new byte[16];
16001        do {
16002            random.nextBytes(bytes);
16003            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16004            result = new File(targetDir, packageName + "-" + suffix);
16005        } while (result.exists());
16006        return result;
16007    }
16008
16009    // Utility method that returns the relative package path with respect
16010    // to the installation directory. Like say for /data/data/com.test-1.apk
16011    // string com.test-1 is returned.
16012    static String deriveCodePathName(String codePath) {
16013        if (codePath == null) {
16014            return null;
16015        }
16016        final File codeFile = new File(codePath);
16017        final String name = codeFile.getName();
16018        if (codeFile.isDirectory()) {
16019            return name;
16020        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16021            final int lastDot = name.lastIndexOf('.');
16022            return name.substring(0, lastDot);
16023        } else {
16024            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16025            return null;
16026        }
16027    }
16028
16029    static class PackageInstalledInfo {
16030        String name;
16031        int uid;
16032        // The set of users that originally had this package installed.
16033        int[] origUsers;
16034        // The set of users that now have this package installed.
16035        int[] newUsers;
16036        PackageParser.Package pkg;
16037        int returnCode;
16038        String returnMsg;
16039        String installerPackageName;
16040        PackageRemovedInfo removedInfo;
16041        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16042
16043        public void setError(int code, String msg) {
16044            setReturnCode(code);
16045            setReturnMessage(msg);
16046            Slog.w(TAG, msg);
16047        }
16048
16049        public void setError(String msg, PackageParserException e) {
16050            setReturnCode(e.error);
16051            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16052            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16053            for (int i = 0; i < childCount; i++) {
16054                addedChildPackages.valueAt(i).setError(msg, e);
16055            }
16056            Slog.w(TAG, msg, e);
16057        }
16058
16059        public void setError(String msg, PackageManagerException e) {
16060            returnCode = e.error;
16061            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16062            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16063            for (int i = 0; i < childCount; i++) {
16064                addedChildPackages.valueAt(i).setError(msg, e);
16065            }
16066            Slog.w(TAG, msg, e);
16067        }
16068
16069        public void setReturnCode(int returnCode) {
16070            this.returnCode = returnCode;
16071            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16072            for (int i = 0; i < childCount; i++) {
16073                addedChildPackages.valueAt(i).returnCode = returnCode;
16074            }
16075        }
16076
16077        private void setReturnMessage(String returnMsg) {
16078            this.returnMsg = returnMsg;
16079            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16080            for (int i = 0; i < childCount; i++) {
16081                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16082            }
16083        }
16084
16085        // In some error cases we want to convey more info back to the observer
16086        String origPackage;
16087        String origPermission;
16088    }
16089
16090    /*
16091     * Install a non-existing package.
16092     */
16093    private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
16094            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
16095            String volumeUuid, PackageInstalledInfo res, int installReason) {
16096        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
16097
16098        // Remember this for later, in case we need to rollback this install
16099        String pkgName = pkg.packageName;
16100
16101        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
16102
16103        synchronized(mPackages) {
16104            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
16105            if (renamedPackage != null) {
16106                // A package with the same name is already installed, though
16107                // it has been renamed to an older name.  The package we
16108                // are trying to install should be installed as an update to
16109                // the existing one, but that has not been requested, so bail.
16110                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16111                        + " without first uninstalling package running as "
16112                        + renamedPackage);
16113                return;
16114            }
16115            if (mPackages.containsKey(pkgName)) {
16116                // Don't allow installation over an existing package with the same name.
16117                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16118                        + " without first uninstalling.");
16119                return;
16120            }
16121        }
16122
16123        try {
16124            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
16125                    System.currentTimeMillis(), user);
16126
16127            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16128
16129            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16130                prepareAppDataAfterInstallLIF(newPackage);
16131
16132            } else {
16133                // Remove package from internal structures, but keep around any
16134                // data that might have already existed
16135                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16136                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16137            }
16138        } catch (PackageManagerException e) {
16139            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16140        }
16141
16142        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16143    }
16144
16145    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16146        try (DigestInputStream digestStream =
16147                new DigestInputStream(new FileInputStream(file), digest)) {
16148            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16149        }
16150    }
16151
16152    private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
16153            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
16154            PackageInstalledInfo res, int installReason) {
16155        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16156
16157        final PackageParser.Package oldPackage;
16158        final PackageSetting ps;
16159        final String pkgName = pkg.packageName;
16160        final int[] allUsers;
16161        final int[] installedUsers;
16162
16163        synchronized(mPackages) {
16164            oldPackage = mPackages.get(pkgName);
16165            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
16166
16167            // don't allow upgrade to target a release SDK from a pre-release SDK
16168            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
16169                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16170            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
16171                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16172            if (oldTargetsPreRelease
16173                    && !newTargetsPreRelease
16174                    && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16175                Slog.w(TAG, "Can't install package targeting released sdk");
16176                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16177                return;
16178            }
16179
16180            ps = mSettings.mPackages.get(pkgName);
16181
16182            // verify signatures are valid
16183            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16184            if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) {
16185                if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) {
16186                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16187                            "New package not signed by keys specified by upgrade-keysets: "
16188                                    + pkgName);
16189                    return;
16190                }
16191            } else {
16192
16193                // default to original signature matching
16194                if (!pkg.mSigningDetails.checkCapability(oldPackage.mSigningDetails,
16195                        PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)) {
16196                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16197                            "New package has a different signature: " + pkgName);
16198                    return;
16199                }
16200            }
16201
16202            // don't allow a system upgrade unless the upgrade hash matches
16203            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) {
16204                byte[] digestBytes = null;
16205                try {
16206                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16207                    updateDigest(digest, new File(pkg.baseCodePath));
16208                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16209                        for (String path : pkg.splitCodePaths) {
16210                            updateDigest(digest, new File(path));
16211                        }
16212                    }
16213                    digestBytes = digest.digest();
16214                } catch (NoSuchAlgorithmException | IOException e) {
16215                    res.setError(INSTALL_FAILED_INVALID_APK,
16216                            "Could not compute hash: " + pkgName);
16217                    return;
16218                }
16219                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16220                    res.setError(INSTALL_FAILED_INVALID_APK,
16221                            "New package fails restrict-update check: " + pkgName);
16222                    return;
16223                }
16224                // retain upgrade restriction
16225                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16226            }
16227
16228            // Check for shared user id changes
16229            String invalidPackageName =
16230                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16231            if (invalidPackageName != null) {
16232                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16233                        "Package " + invalidPackageName + " tried to change user "
16234                                + oldPackage.mSharedUserId);
16235                return;
16236            }
16237
16238            // check if the new package supports all of the abis which the old package supports
16239            boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null;
16240            boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null;
16241            if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) {
16242                res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16243                        "Update to package " + pkgName + " doesn't support multi arch");
16244                return;
16245            }
16246
16247            // In case of rollback, remember per-user/profile install state
16248            allUsers = sUserManager.getUserIds();
16249            installedUsers = ps.queryInstalledUsers(allUsers, true);
16250
16251            // don't allow an upgrade from full to ephemeral
16252            if (isInstantApp) {
16253                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16254                    for (int currentUser : allUsers) {
16255                        if (!ps.getInstantApp(currentUser)) {
16256                            // can't downgrade from full to instant
16257                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16258                                    + " for user: " + currentUser);
16259                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16260                            return;
16261                        }
16262                    }
16263                } else if (!ps.getInstantApp(user.getIdentifier())) {
16264                    // can't downgrade from full to instant
16265                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16266                            + " for user: " + user.getIdentifier());
16267                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16268                    return;
16269                }
16270            }
16271        }
16272
16273        // Update what is removed
16274        res.removedInfo = new PackageRemovedInfo(this);
16275        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16276        res.removedInfo.removedPackage = oldPackage.packageName;
16277        res.removedInfo.installerPackageName = ps.installerPackageName;
16278        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16279        res.removedInfo.isUpdate = true;
16280        res.removedInfo.origUsers = installedUsers;
16281        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16282        for (int i = 0; i < installedUsers.length; i++) {
16283            final int userId = installedUsers[i];
16284            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16285        }
16286
16287        final int childCount = (oldPackage.childPackages != null)
16288                ? oldPackage.childPackages.size() : 0;
16289        for (int i = 0; i < childCount; i++) {
16290            boolean childPackageUpdated = false;
16291            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16292            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16293            if (res.addedChildPackages != null) {
16294                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16295                if (childRes != null) {
16296                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16297                    childRes.removedInfo.removedPackage = childPkg.packageName;
16298                    if (childPs != null) {
16299                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16300                    }
16301                    childRes.removedInfo.isUpdate = true;
16302                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16303                    childPackageUpdated = true;
16304                }
16305            }
16306            if (!childPackageUpdated) {
16307                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16308                childRemovedRes.removedPackage = childPkg.packageName;
16309                if (childPs != null) {
16310                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16311                }
16312                childRemovedRes.isUpdate = false;
16313                childRemovedRes.dataRemoved = true;
16314                synchronized (mPackages) {
16315                    if (childPs != null) {
16316                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16317                    }
16318                }
16319                if (res.removedInfo.removedChildPackages == null) {
16320                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16321                }
16322                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16323            }
16324        }
16325
16326        boolean sysPkg = (isSystemApp(oldPackage));
16327        if (sysPkg) {
16328            // Set the system/privileged/oem/vendor/product flags as needed
16329            final boolean privileged =
16330                    (oldPackage.applicationInfo.privateFlags
16331                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16332            final boolean oem =
16333                    (oldPackage.applicationInfo.privateFlags
16334                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
16335            final boolean vendor =
16336                    (oldPackage.applicationInfo.privateFlags
16337                            & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
16338            final boolean product =
16339                    (oldPackage.applicationInfo.privateFlags
16340                            & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
16341            final @ParseFlags int systemParseFlags = parseFlags;
16342            final @ScanFlags int systemScanFlags = scanFlags
16343                    | SCAN_AS_SYSTEM
16344                    | (privileged ? SCAN_AS_PRIVILEGED : 0)
16345                    | (oem ? SCAN_AS_OEM : 0)
16346                    | (vendor ? SCAN_AS_VENDOR : 0)
16347                    | (product ? SCAN_AS_PRODUCT : 0);
16348
16349            replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags,
16350                    user, allUsers, installerPackageName, res, installReason);
16351        } else {
16352            replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags,
16353                    user, allUsers, installerPackageName, res, installReason);
16354        }
16355    }
16356
16357    @Override
16358    public List<String> getPreviousCodePaths(String packageName) {
16359        final int callingUid = Binder.getCallingUid();
16360        final List<String> result = new ArrayList<>();
16361        if (getInstantAppPackageName(callingUid) != null) {
16362            return result;
16363        }
16364        final PackageSetting ps = mSettings.mPackages.get(packageName);
16365        if (ps != null
16366                && ps.oldCodePaths != null
16367                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
16368            result.addAll(ps.oldCodePaths);
16369        }
16370        return result;
16371    }
16372
16373    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16374            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16375            final @ScanFlags int scanFlags, UserHandle user, int[] allUsers,
16376            String installerPackageName, PackageInstalledInfo res, int installReason) {
16377        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16378                + deletedPackage);
16379
16380        String pkgName = deletedPackage.packageName;
16381        boolean deletedPkg = true;
16382        boolean addedPkg = false;
16383        boolean updatedSettings = false;
16384        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16385        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16386                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16387
16388        final long origUpdateTime = (pkg.mExtras != null)
16389                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16390
16391        // First delete the existing package while retaining the data directory
16392        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16393                res.removedInfo, true, pkg)) {
16394            // If the existing package wasn't successfully deleted
16395            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16396            deletedPkg = false;
16397        } else {
16398            // Successfully deleted the old package; proceed with replace.
16399
16400            // If deleted package lived in a container, give users a chance to
16401            // relinquish resources before killing.
16402            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16403                if (DEBUG_INSTALL) {
16404                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16405                }
16406                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16407                final ArrayList<String> pkgList = new ArrayList<String>(1);
16408                pkgList.add(deletedPackage.applicationInfo.packageName);
16409                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16410            }
16411
16412            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16413                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16414
16415            try {
16416                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
16417                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16418                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16419                        installReason);
16420
16421                // Update the in-memory copy of the previous code paths.
16422                PackageSetting ps = mSettings.mPackages.get(pkgName);
16423                if (!killApp) {
16424                    if (ps.oldCodePaths == null) {
16425                        ps.oldCodePaths = new ArraySet<>();
16426                    }
16427                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16428                    if (deletedPackage.splitCodePaths != null) {
16429                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16430                    }
16431                } else {
16432                    ps.oldCodePaths = null;
16433                }
16434                if (ps.childPackageNames != null) {
16435                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16436                        final String childPkgName = ps.childPackageNames.get(i);
16437                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16438                        childPs.oldCodePaths = ps.oldCodePaths;
16439                    }
16440                }
16441                // set instant app status, but, only if it's explicitly specified
16442                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16443                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16444                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16445                prepareAppDataAfterInstallLIF(newPackage);
16446                addedPkg = true;
16447                mDexManager.notifyPackageUpdated(newPackage.packageName,
16448                        newPackage.baseCodePath, newPackage.splitCodePaths);
16449            } catch (PackageManagerException e) {
16450                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16451            }
16452        }
16453
16454        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16455            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16456
16457            // Revert all internal state mutations and added folders for the failed install
16458            if (addedPkg) {
16459                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16460                        res.removedInfo, true, null);
16461            }
16462
16463            // Restore the old package
16464            if (deletedPkg) {
16465                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16466                File restoreFile = new File(deletedPackage.codePath);
16467                // Parse old package
16468                boolean oldExternal = isExternal(deletedPackage);
16469                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16470                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16471                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16472                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16473                try {
16474                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16475                            null);
16476                } catch (PackageManagerException e) {
16477                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16478                            + e.getMessage());
16479                    return;
16480                }
16481
16482                synchronized (mPackages) {
16483                    // Ensure the installer package name up to date
16484                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16485
16486                    // Update permissions for restored package
16487                    mPermissionManager.updatePermissions(
16488                            deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16489                            mPermissionCallback);
16490
16491                    mSettings.writeLPr();
16492                }
16493
16494                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16495            }
16496        } else {
16497            synchronized (mPackages) {
16498                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16499                if (ps != null) {
16500                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16501                    if (res.removedInfo.removedChildPackages != null) {
16502                        final int childCount = res.removedInfo.removedChildPackages.size();
16503                        // Iterate in reverse as we may modify the collection
16504                        for (int i = childCount - 1; i >= 0; i--) {
16505                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16506                            if (res.addedChildPackages.containsKey(childPackageName)) {
16507                                res.removedInfo.removedChildPackages.removeAt(i);
16508                            } else {
16509                                PackageRemovedInfo childInfo = res.removedInfo
16510                                        .removedChildPackages.valueAt(i);
16511                                childInfo.removedForAllUsers = mPackages.get(
16512                                        childInfo.removedPackage) == null;
16513                            }
16514                        }
16515                    }
16516                }
16517            }
16518        }
16519    }
16520
16521    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16522            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16523            final @ScanFlags int scanFlags, UserHandle user,
16524            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16525            int installReason) {
16526        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16527                + ", old=" + deletedPackage);
16528
16529        final boolean disabledSystem;
16530
16531        // Remove existing system package
16532        removePackageLI(deletedPackage, true);
16533
16534        synchronized (mPackages) {
16535            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16536        }
16537        if (!disabledSystem) {
16538            // We didn't need to disable the .apk as a current system package,
16539            // which means we are replacing another update that is already
16540            // installed.  We need to make sure to delete the older one's .apk.
16541            res.removedInfo.args = createInstallArgsForExisting(0,
16542                    deletedPackage.applicationInfo.getCodePath(),
16543                    deletedPackage.applicationInfo.getResourcePath(),
16544                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16545        } else {
16546            res.removedInfo.args = null;
16547        }
16548
16549        // Successfully disabled the old package. Now proceed with re-installation
16550        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16551                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16552
16553        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16554        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16555                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16556
16557        PackageParser.Package newPackage = null;
16558        try {
16559            // Add the package to the internal data structures
16560            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
16561
16562            // Set the update and install times
16563            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16564            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16565                    System.currentTimeMillis());
16566
16567            // Update the package dynamic state if succeeded
16568            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16569                // Now that the install succeeded make sure we remove data
16570                // directories for any child package the update removed.
16571                final int deletedChildCount = (deletedPackage.childPackages != null)
16572                        ? deletedPackage.childPackages.size() : 0;
16573                final int newChildCount = (newPackage.childPackages != null)
16574                        ? newPackage.childPackages.size() : 0;
16575                for (int i = 0; i < deletedChildCount; i++) {
16576                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16577                    boolean childPackageDeleted = true;
16578                    for (int j = 0; j < newChildCount; j++) {
16579                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16580                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16581                            childPackageDeleted = false;
16582                            break;
16583                        }
16584                    }
16585                    if (childPackageDeleted) {
16586                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16587                                deletedChildPkg.packageName);
16588                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16589                            PackageRemovedInfo removedChildRes = res.removedInfo
16590                                    .removedChildPackages.get(deletedChildPkg.packageName);
16591                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16592                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16593                        }
16594                    }
16595                }
16596
16597                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16598                        installReason);
16599                prepareAppDataAfterInstallLIF(newPackage);
16600
16601                mDexManager.notifyPackageUpdated(newPackage.packageName,
16602                            newPackage.baseCodePath, newPackage.splitCodePaths);
16603            }
16604        } catch (PackageManagerException e) {
16605            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16606            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16607        }
16608
16609        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16610            // Re installation failed. Restore old information
16611            // Remove new pkg information
16612            if (newPackage != null) {
16613                removeInstalledPackageLI(newPackage, true);
16614            }
16615            // Add back the old system package
16616            try {
16617                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16618            } catch (PackageManagerException e) {
16619                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16620            }
16621
16622            synchronized (mPackages) {
16623                if (disabledSystem) {
16624                    enableSystemPackageLPw(deletedPackage);
16625                }
16626
16627                // Ensure the installer package name up to date
16628                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16629
16630                // Update permissions for restored package
16631                mPermissionManager.updatePermissions(
16632                        deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16633                        mPermissionCallback);
16634
16635                mSettings.writeLPr();
16636            }
16637
16638            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16639                    + " after failed upgrade");
16640        }
16641    }
16642
16643    /**
16644     * Checks whether the parent or any of the child packages have a change shared
16645     * user. For a package to be a valid update the shred users of the parent and
16646     * the children should match. We may later support changing child shared users.
16647     * @param oldPkg The updated package.
16648     * @param newPkg The update package.
16649     * @return The shared user that change between the versions.
16650     */
16651    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16652            PackageParser.Package newPkg) {
16653        // Check parent shared user
16654        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16655            return newPkg.packageName;
16656        }
16657        // Check child shared users
16658        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16659        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16660        for (int i = 0; i < newChildCount; i++) {
16661            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16662            // If this child was present, did it have the same shared user?
16663            for (int j = 0; j < oldChildCount; j++) {
16664                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16665                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16666                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16667                    return newChildPkg.packageName;
16668                }
16669            }
16670        }
16671        return null;
16672    }
16673
16674    private void removeNativeBinariesLI(PackageSetting ps) {
16675        // Remove the lib path for the parent package
16676        if (ps != null) {
16677            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16678            // Remove the lib path for the child packages
16679            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16680            for (int i = 0; i < childCount; i++) {
16681                PackageSetting childPs = null;
16682                synchronized (mPackages) {
16683                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16684                }
16685                if (childPs != null) {
16686                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16687                            .legacyNativeLibraryPathString);
16688                }
16689            }
16690        }
16691    }
16692
16693    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16694        // Enable the parent package
16695        mSettings.enableSystemPackageLPw(pkg.packageName);
16696        // Enable the child packages
16697        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16698        for (int i = 0; i < childCount; i++) {
16699            PackageParser.Package childPkg = pkg.childPackages.get(i);
16700            mSettings.enableSystemPackageLPw(childPkg.packageName);
16701        }
16702    }
16703
16704    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16705            PackageParser.Package newPkg) {
16706        // Disable the parent package (parent always replaced)
16707        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16708        // Disable the child packages
16709        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16710        for (int i = 0; i < childCount; i++) {
16711            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16712            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16713            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16714        }
16715        return disabled;
16716    }
16717
16718    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16719            String installerPackageName) {
16720        // Enable the parent package
16721        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16722        // Enable the child packages
16723        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16724        for (int i = 0; i < childCount; i++) {
16725            PackageParser.Package childPkg = pkg.childPackages.get(i);
16726            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16727        }
16728    }
16729
16730    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16731            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16732        // Update the parent package setting
16733        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16734                res, user, installReason);
16735        // Update the child packages setting
16736        final int childCount = (newPackage.childPackages != null)
16737                ? newPackage.childPackages.size() : 0;
16738        for (int i = 0; i < childCount; i++) {
16739            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16740            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16741            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16742                    childRes.origUsers, childRes, user, installReason);
16743        }
16744    }
16745
16746    private void updateSettingsInternalLI(PackageParser.Package pkg,
16747            String installerPackageName, int[] allUsers, int[] installedForUsers,
16748            PackageInstalledInfo res, UserHandle user, int installReason) {
16749        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16750
16751        final String pkgName = pkg.packageName;
16752
16753        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath);
16754        synchronized (mPackages) {
16755// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions
16756            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
16757                    mPermissionCallback);
16758            // For system-bundled packages, we assume that installing an upgraded version
16759            // of the package implies that the user actually wants to run that new code,
16760            // so we enable the package.
16761            PackageSetting ps = mSettings.mPackages.get(pkgName);
16762            final int userId = user.getIdentifier();
16763            if (ps != null) {
16764                if (isSystemApp(pkg)) {
16765                    if (DEBUG_INSTALL) {
16766                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16767                    }
16768                    // Enable system package for requested users
16769                    if (res.origUsers != null) {
16770                        for (int origUserId : res.origUsers) {
16771                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16772                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16773                                        origUserId, installerPackageName);
16774                            }
16775                        }
16776                    }
16777                    // Also convey the prior install/uninstall state
16778                    if (allUsers != null && installedForUsers != null) {
16779                        for (int currentUserId : allUsers) {
16780                            final boolean installed = ArrayUtils.contains(
16781                                    installedForUsers, currentUserId);
16782                            if (DEBUG_INSTALL) {
16783                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16784                            }
16785                            ps.setInstalled(installed, currentUserId);
16786                        }
16787                        // these install state changes will be persisted in the
16788                        // upcoming call to mSettings.writeLPr().
16789                    }
16790                }
16791                // It's implied that when a user requests installation, they want the app to be
16792                // installed and enabled.
16793                if (userId != UserHandle.USER_ALL) {
16794                    ps.setInstalled(true, userId);
16795                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16796                } else {
16797                    for (int currentUserId : sUserManager.getUserIds()) {
16798                        ps.setInstalled(true, currentUserId);
16799                        ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, currentUserId,
16800                                installerPackageName);
16801                    }
16802                }
16803
16804                // When replacing an existing package, preserve the original install reason for all
16805                // users that had the package installed before.
16806                final Set<Integer> previousUserIds = new ArraySet<>();
16807                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16808                    final int installReasonCount = res.removedInfo.installReasons.size();
16809                    for (int i = 0; i < installReasonCount; i++) {
16810                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16811                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16812                        ps.setInstallReason(previousInstallReason, previousUserId);
16813                        previousUserIds.add(previousUserId);
16814                    }
16815                }
16816
16817                // Set install reason for users that are having the package newly installed.
16818                if (userId == UserHandle.USER_ALL) {
16819                    for (int currentUserId : sUserManager.getUserIds()) {
16820                        if (!previousUserIds.contains(currentUserId)) {
16821                            ps.setInstallReason(installReason, currentUserId);
16822                        }
16823                    }
16824                } else if (!previousUserIds.contains(userId)) {
16825                    ps.setInstallReason(installReason, userId);
16826                }
16827                mSettings.writeKernelMappingLPr(ps);
16828            }
16829            res.name = pkgName;
16830            res.uid = pkg.applicationInfo.uid;
16831            res.pkg = pkg;
16832            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16833            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16834            //to update install status
16835            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16836            mSettings.writeLPr();
16837            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16838        }
16839
16840        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16841    }
16842
16843    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16844        try {
16845            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16846            installPackageLI(args, res);
16847        } finally {
16848            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16849        }
16850    }
16851
16852    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16853        final int installFlags = args.installFlags;
16854        final String installerPackageName = args.installerPackageName;
16855        final String volumeUuid = args.volumeUuid;
16856        final File tmpPackageFile = new File(args.getCodePath());
16857        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16858        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16859                || (args.volumeUuid != null));
16860        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16861        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16862        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16863        final boolean virtualPreload =
16864                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
16865        boolean replace = false;
16866        @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16867        if (args.move != null) {
16868            // moving a complete application; perform an initial scan on the new install location
16869            scanFlags |= SCAN_INITIAL;
16870        }
16871        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16872            scanFlags |= SCAN_DONT_KILL_APP;
16873        }
16874        if (instantApp) {
16875            scanFlags |= SCAN_AS_INSTANT_APP;
16876        }
16877        if (fullApp) {
16878            scanFlags |= SCAN_AS_FULL_APP;
16879        }
16880        if (virtualPreload) {
16881            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
16882        }
16883
16884        // Result object to be returned
16885        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16886        res.installerPackageName = installerPackageName;
16887
16888        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16889
16890        // Sanity check
16891        if (instantApp && (forwardLocked || onExternal)) {
16892            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16893                    + " external=" + onExternal);
16894            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16895            return;
16896        }
16897
16898        // Retrieve PackageSettings and parse package
16899        @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16900                | PackageParser.PARSE_ENFORCE_CODE
16901                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16902                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16903                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16904        PackageParser pp = new PackageParser();
16905        pp.setSeparateProcesses(mSeparateProcesses);
16906        pp.setDisplayMetrics(mMetrics);
16907        pp.setCallback(mPackageParserCallback);
16908
16909        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16910        final PackageParser.Package pkg;
16911        try {
16912            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16913            DexMetadataHelper.validatePackageDexMetadata(pkg);
16914        } catch (PackageParserException e) {
16915            res.setError("Failed parse during installPackageLI", e);
16916            return;
16917        } finally {
16918            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16919        }
16920
16921        // Instant apps have several additional install-time checks.
16922        if (instantApp) {
16923            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
16924                Slog.w(TAG,
16925                        "Instant app package " + pkg.packageName + " does not target at least O");
16926                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16927                        "Instant app package must target at least O");
16928                return;
16929            }
16930            if (pkg.applicationInfo.targetSandboxVersion != 2) {
16931                Slog.w(TAG, "Instant app package " + pkg.packageName
16932                        + " does not target targetSandboxVersion 2");
16933                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16934                        "Instant app package must use targetSandboxVersion 2");
16935                return;
16936            }
16937            if (pkg.mSharedUserId != null) {
16938                Slog.w(TAG, "Instant app package " + pkg.packageName
16939                        + " may not declare sharedUserId.");
16940                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16941                        "Instant app package may not declare a sharedUserId");
16942                return;
16943            }
16944        }
16945
16946        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16947            // Static shared libraries have synthetic package names
16948            renameStaticSharedLibraryPackage(pkg);
16949
16950            // No static shared libs on external storage
16951            if (onExternal) {
16952                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16953                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16954                        "Packages declaring static-shared libs cannot be updated");
16955                return;
16956            }
16957        }
16958
16959        // If we are installing a clustered package add results for the children
16960        if (pkg.childPackages != null) {
16961            synchronized (mPackages) {
16962                final int childCount = pkg.childPackages.size();
16963                for (int i = 0; i < childCount; i++) {
16964                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16965                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16966                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16967                    childRes.pkg = childPkg;
16968                    childRes.name = childPkg.packageName;
16969                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16970                    if (childPs != null) {
16971                        childRes.origUsers = childPs.queryInstalledUsers(
16972                                sUserManager.getUserIds(), true);
16973                    }
16974                    if ((mPackages.containsKey(childPkg.packageName))) {
16975                        childRes.removedInfo = new PackageRemovedInfo(this);
16976                        childRes.removedInfo.removedPackage = childPkg.packageName;
16977                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16978                    }
16979                    if (res.addedChildPackages == null) {
16980                        res.addedChildPackages = new ArrayMap<>();
16981                    }
16982                    res.addedChildPackages.put(childPkg.packageName, childRes);
16983                }
16984            }
16985        }
16986
16987        // If package doesn't declare API override, mark that we have an install
16988        // time CPU ABI override.
16989        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16990            pkg.cpuAbiOverride = args.abiOverride;
16991        }
16992
16993        String pkgName = res.name = pkg.packageName;
16994        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16995            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16996                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16997                return;
16998            }
16999        }
17000
17001        try {
17002            // either use what we've been given or parse directly from the APK
17003            if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) {
17004                pkg.setSigningDetails(args.signingDetails);
17005            } else {
17006                PackageParser.collectCertificates(pkg, false /* skipVerify */);
17007            }
17008        } catch (PackageParserException e) {
17009            res.setError("Failed collect during installPackageLI", e);
17010            return;
17011        }
17012
17013        if (instantApp && pkg.mSigningDetails.signatureSchemeVersion
17014                < SignatureSchemeVersion.SIGNING_BLOCK_V2) {
17015            Slog.w(TAG, "Instant app package " + pkg.packageName
17016                    + " is not signed with at least APK Signature Scheme v2");
17017            res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17018                    "Instant app package must be signed with APK Signature Scheme v2 or greater");
17019            return;
17020        }
17021
17022        // Get rid of all references to package scan path via parser.
17023        pp = null;
17024        String oldCodePath = null;
17025        boolean systemApp = false;
17026        synchronized (mPackages) {
17027            // Check if installing already existing package
17028            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
17029                String oldName = mSettings.getRenamedPackageLPr(pkgName);
17030                if (pkg.mOriginalPackages != null
17031                        && pkg.mOriginalPackages.contains(oldName)
17032                        && mPackages.containsKey(oldName)) {
17033                    // This package is derived from an original package,
17034                    // and this device has been updating from that original
17035                    // name.  We must continue using the original name, so
17036                    // rename the new package here.
17037                    pkg.setPackageName(oldName);
17038                    pkgName = pkg.packageName;
17039                    replace = true;
17040                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
17041                            + oldName + " pkgName=" + pkgName);
17042                } else if (mPackages.containsKey(pkgName)) {
17043                    // This package, under its official name, already exists
17044                    // on the device; we should replace it.
17045                    replace = true;
17046                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
17047                }
17048
17049                // Child packages are installed through the parent package
17050                if (pkg.parentPackage != null) {
17051                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17052                            "Package " + pkg.packageName + " is child of package "
17053                                    + pkg.parentPackage.parentPackage + ". Child packages "
17054                                    + "can be updated only through the parent package.");
17055                    return;
17056                }
17057
17058                if (replace) {
17059                    // Prevent apps opting out from runtime permissions
17060                    PackageParser.Package oldPackage = mPackages.get(pkgName);
17061                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
17062                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
17063                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
17064                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
17065                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
17066                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
17067                                        + " doesn't support runtime permissions but the old"
17068                                        + " target SDK " + oldTargetSdk + " does.");
17069                        return;
17070                    }
17071                    // Prevent persistent apps from being updated
17072                    if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) {
17073                        res.setError(PackageManager.INSTALL_FAILED_INVALID_APK,
17074                                "Package " + oldPackage.packageName + " is a persistent app. "
17075                                        + "Persistent apps are not updateable.");
17076                        return;
17077                    }
17078                    // Prevent apps from downgrading their targetSandbox.
17079                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
17080                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
17081                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
17082                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17083                                "Package " + pkg.packageName + " new target sandbox "
17084                                + newTargetSandbox + " is incompatible with the previous value of"
17085                                + oldTargetSandbox + ".");
17086                        return;
17087                    }
17088
17089                    // Prevent installing of child packages
17090                    if (oldPackage.parentPackage != null) {
17091                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17092                                "Package " + pkg.packageName + " is child of package "
17093                                        + oldPackage.parentPackage + ". Child packages "
17094                                        + "can be updated only through the parent package.");
17095                        return;
17096                    }
17097                }
17098            }
17099
17100            PackageSetting ps = mSettings.mPackages.get(pkgName);
17101            if (ps != null) {
17102                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
17103
17104                // Static shared libs have same package with different versions where
17105                // we internally use a synthetic package name to allow multiple versions
17106                // of the same package, therefore we need to compare signatures against
17107                // the package setting for the latest library version.
17108                PackageSetting signatureCheckPs = ps;
17109                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17110                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
17111                    if (libraryEntry != null) {
17112                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17113                    }
17114                }
17115
17116                // Quick sanity check that we're signed correctly if updating;
17117                // we'll check this again later when scanning, but we want to
17118                // bail early here before tripping over redefined permissions.
17119                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17120                if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
17121                    if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
17122                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17123                                + pkg.packageName + " upgrade keys do not match the "
17124                                + "previously installed version");
17125                        return;
17126                    }
17127                } else {
17128                    try {
17129                        final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
17130                        final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
17131                        // We don't care about disabledPkgSetting on install for now.
17132                        final boolean compatMatch = verifySignatures(
17133                                signatureCheckPs, null, pkg.mSigningDetails, compareCompat,
17134                                compareRecover);
17135                        // The new KeySets will be re-added later in the scanning process.
17136                        if (compatMatch) {
17137                            synchronized (mPackages) {
17138                                ksms.removeAppKeySetDataLPw(pkg.packageName);
17139                            }
17140                        }
17141                    } catch (PackageManagerException e) {
17142                        res.setError(e.error, e.getMessage());
17143                        return;
17144                    }
17145                }
17146
17147                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17148                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17149                    systemApp = (ps.pkg.applicationInfo.flags &
17150                            ApplicationInfo.FLAG_SYSTEM) != 0;
17151                }
17152                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17153            }
17154
17155            int N = pkg.permissions.size();
17156            for (int i = N-1; i >= 0; i--) {
17157                final PackageParser.Permission perm = pkg.permissions.get(i);
17158                final BasePermission bp =
17159                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
17160
17161                // Don't allow anyone but the system to define ephemeral permissions.
17162                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
17163                        && !systemApp) {
17164                    Slog.w(TAG, "Non-System package " + pkg.packageName
17165                            + " attempting to delcare ephemeral permission "
17166                            + perm.info.name + "; Removing ephemeral.");
17167                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
17168                }
17169
17170                // Check whether the newly-scanned package wants to define an already-defined perm
17171                if (bp != null) {
17172                    // If the defining package is signed with our cert, it's okay.  This
17173                    // also includes the "updating the same package" case, of course.
17174                    // "updating same package" could also involve key-rotation.
17175                    final boolean sigsOk;
17176                    final String sourcePackageName = bp.getSourcePackageName();
17177                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
17178                    final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17179                    if (sourcePackageName.equals(pkg.packageName)
17180                            && (ksms.shouldCheckUpgradeKeySetLocked(
17181                                    sourcePackageSetting, scanFlags))) {
17182                        sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg);
17183                    } else {
17184
17185                        // in the event of signing certificate rotation, we need to see if the
17186                        // package's certificate has rotated from the current one, or if it is an
17187                        // older certificate with which the current is ok with sharing permissions
17188                        if (sourcePackageSetting.signatures.mSigningDetails.checkCapability(
17189                                        pkg.mSigningDetails,
17190                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17191                            sigsOk = true;
17192                        } else if (pkg.mSigningDetails.checkCapability(
17193                                        sourcePackageSetting.signatures.mSigningDetails,
17194                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17195
17196                            // the scanned package checks out, has signing certificate rotation
17197                            // history, and is newer; bring it over
17198                            sourcePackageSetting.signatures.mSigningDetails = pkg.mSigningDetails;
17199                            sigsOk = true;
17200                        } else {
17201                            sigsOk = false;
17202                        }
17203                    }
17204                    if (!sigsOk) {
17205                        // If the owning package is the system itself, we log but allow
17206                        // install to proceed; we fail the install on all other permission
17207                        // redefinitions.
17208                        if (!sourcePackageName.equals("android")) {
17209                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17210                                    + pkg.packageName + " attempting to redeclare permission "
17211                                    + perm.info.name + " already owned by " + sourcePackageName);
17212                            res.origPermission = perm.info.name;
17213                            res.origPackage = sourcePackageName;
17214                            return;
17215                        } else {
17216                            Slog.w(TAG, "Package " + pkg.packageName
17217                                    + " attempting to redeclare system permission "
17218                                    + perm.info.name + "; ignoring new declaration");
17219                            pkg.permissions.remove(i);
17220                        }
17221                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17222                        // Prevent apps to change protection level to dangerous from any other
17223                        // type as this would allow a privilege escalation where an app adds a
17224                        // normal/signature permission in other app's group and later redefines
17225                        // it as dangerous leading to the group auto-grant.
17226                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17227                                == PermissionInfo.PROTECTION_DANGEROUS) {
17228                            if (bp != null && !bp.isRuntime()) {
17229                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17230                                        + "non-runtime permission " + perm.info.name
17231                                        + " to runtime; keeping old protection level");
17232                                perm.info.protectionLevel = bp.getProtectionLevel();
17233                            }
17234                        }
17235                    }
17236                }
17237            }
17238        }
17239
17240        if (systemApp) {
17241            if (onExternal) {
17242                // Abort update; system app can't be replaced with app on sdcard
17243                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17244                        "Cannot install updates to system apps on sdcard");
17245                return;
17246            } else if (instantApp) {
17247                // Abort update; system app can't be replaced with an instant app
17248                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17249                        "Cannot update a system app with an instant app");
17250                return;
17251            }
17252        }
17253
17254        if (args.move != null) {
17255            // We did an in-place move, so dex is ready to roll
17256            scanFlags |= SCAN_NO_DEX;
17257            scanFlags |= SCAN_MOVE;
17258
17259            synchronized (mPackages) {
17260                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17261                if (ps == null) {
17262                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17263                            "Missing settings for moved package " + pkgName);
17264                }
17265
17266                // We moved the entire application as-is, so bring over the
17267                // previously derived ABI information.
17268                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17269                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17270            }
17271
17272        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17273            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17274            scanFlags |= SCAN_NO_DEX;
17275
17276            try {
17277                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17278                    args.abiOverride : pkg.cpuAbiOverride);
17279                final boolean extractNativeLibs = !pkg.isLibrary();
17280                derivePackageAbi(pkg, abiOverride, extractNativeLibs);
17281            } catch (PackageManagerException pme) {
17282                Slog.e(TAG, "Error deriving application ABI", pme);
17283                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17284                return;
17285            }
17286
17287            // Shared libraries for the package need to be updated.
17288            synchronized (mPackages) {
17289                try {
17290                    updateSharedLibrariesLPr(pkg, null);
17291                } catch (PackageManagerException e) {
17292                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17293                }
17294            }
17295        }
17296
17297        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17298            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17299            return;
17300        }
17301
17302        if (PackageManagerServiceUtils.isApkVerityEnabled()) {
17303            String apkPath = null;
17304            synchronized (mPackages) {
17305                // Note that if the attacker managed to skip verify setup, for example by tampering
17306                // with the package settings, upon reboot we will do full apk verification when
17307                // verity is not detected.
17308                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17309                if (ps != null && ps.isPrivileged()) {
17310                    apkPath = pkg.baseCodePath;
17311                }
17312            }
17313
17314            if (apkPath != null) {
17315                final VerityUtils.SetupResult result =
17316                        VerityUtils.generateApkVeritySetupData(apkPath);
17317                if (result.isOk()) {
17318                    if (Build.IS_DEBUGGABLE) Slog.i(TAG, "Enabling apk verity to " + apkPath);
17319                    FileDescriptor fd = result.getUnownedFileDescriptor();
17320                    try {
17321                        mInstaller.installApkVerity(apkPath, fd);
17322                    } catch (InstallerException e) {
17323                        res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17324                                "Failed to set up verity: " + e);
17325                        return;
17326                    } finally {
17327                        IoUtils.closeQuietly(fd);
17328                    }
17329                } else if (result.isFailed()) {
17330                    res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Failed to generate verity");
17331                    return;
17332                } else {
17333                    // Do nothing if verity is skipped. Will fall back to full apk verification on
17334                    // reboot.
17335                }
17336            }
17337        }
17338
17339        if (!instantApp) {
17340            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17341        } else {
17342            if (DEBUG_DOMAIN_VERIFICATION) {
17343                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
17344            }
17345        }
17346
17347        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17348                "installPackageLI")) {
17349            if (replace) {
17350                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17351                    // Static libs have a synthetic package name containing the version
17352                    // and cannot be updated as an update would get a new package name,
17353                    // unless this is the exact same version code which is useful for
17354                    // development.
17355                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17356                    if (existingPkg != null &&
17357                            existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) {
17358                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17359                                + "static-shared libs cannot be updated");
17360                        return;
17361                    }
17362                }
17363                replacePackageLIF(pkg, parseFlags, scanFlags, args.user,
17364                        installerPackageName, res, args.installReason);
17365            } else {
17366                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17367                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17368            }
17369        }
17370
17371        // Prepare the application profiles for the new code paths.
17372        // This needs to be done before invoking dexopt so that any install-time profile
17373        // can be used for optimizations.
17374        mArtManagerService.prepareAppProfiles(pkg, resolveUserIds(args.user.getIdentifier()));
17375
17376        // Check whether we need to dexopt the app.
17377        //
17378        // NOTE: it is IMPORTANT to call dexopt:
17379        //   - after doRename which will sync the package data from PackageParser.Package and its
17380        //     corresponding ApplicationInfo.
17381        //   - after installNewPackageLIF or replacePackageLIF which will update result with the
17382        //     uid of the application (pkg.applicationInfo.uid).
17383        //     This update happens in place!
17384        //
17385        // We only need to dexopt if the package meets ALL of the following conditions:
17386        //   1) it is not forward locked.
17387        //   2) it is not on on an external ASEC container.
17388        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
17389        //
17390        // Note that we do not dexopt instant apps by default. dexopt can take some time to
17391        // complete, so we skip this step during installation. Instead, we'll take extra time
17392        // the first time the instant app starts. It's preferred to do it this way to provide
17393        // continuous progress to the useur instead of mysteriously blocking somewhere in the
17394        // middle of running an instant app. The default behaviour can be overridden
17395        // via gservices.
17396        final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED)
17397                && !forwardLocked
17398                && !pkg.applicationInfo.isExternalAsec()
17399                && (!instantApp || Global.getInt(mContext.getContentResolver(),
17400                Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
17401
17402        if (performDexopt) {
17403            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17404            // Do not run PackageDexOptimizer through the local performDexOpt
17405            // method because `pkg` may not be in `mPackages` yet.
17406            //
17407            // Also, don't fail application installs if the dexopt step fails.
17408            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
17409                    REASON_INSTALL,
17410                    DexoptOptions.DEXOPT_BOOT_COMPLETE |
17411                    DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE);
17412            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17413                    null /* instructionSets */,
17414                    getOrCreateCompilerPackageStats(pkg),
17415                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
17416                    dexoptOptions);
17417            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17418        }
17419
17420        // Notify BackgroundDexOptService that the package has been changed.
17421        // If this is an update of a package which used to fail to compile,
17422        // BackgroundDexOptService will remove it from its blacklist.
17423        // TODO: Layering violation
17424        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17425
17426        synchronized (mPackages) {
17427            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17428            if (ps != null) {
17429                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17430                ps.setUpdateAvailable(false /*updateAvailable*/);
17431            }
17432
17433            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17434            for (int i = 0; i < childCount; i++) {
17435                PackageParser.Package childPkg = pkg.childPackages.get(i);
17436                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17437                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17438                if (childPs != null) {
17439                    childRes.newUsers = childPs.queryInstalledUsers(
17440                            sUserManager.getUserIds(), true);
17441                }
17442            }
17443
17444            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17445                updateSequenceNumberLP(ps, res.newUsers);
17446                updateInstantAppInstallerLocked(pkgName);
17447            }
17448        }
17449    }
17450
17451    private void startIntentFilterVerifications(int userId, boolean replacing,
17452            PackageParser.Package pkg) {
17453        if (mIntentFilterVerifierComponent == null) {
17454            Slog.w(TAG, "No IntentFilter verification will not be done as "
17455                    + "there is no IntentFilterVerifier available!");
17456            return;
17457        }
17458
17459        final int verifierUid = getPackageUid(
17460                mIntentFilterVerifierComponent.getPackageName(),
17461                MATCH_DEBUG_TRIAGED_MISSING,
17462                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17463
17464        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17465        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17466        mHandler.sendMessage(msg);
17467
17468        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17469        for (int i = 0; i < childCount; i++) {
17470            PackageParser.Package childPkg = pkg.childPackages.get(i);
17471            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17472            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17473            mHandler.sendMessage(msg);
17474        }
17475    }
17476
17477    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17478            PackageParser.Package pkg) {
17479        int size = pkg.activities.size();
17480        if (size == 0) {
17481            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17482                    "No activity, so no need to verify any IntentFilter!");
17483            return;
17484        }
17485
17486        final boolean hasDomainURLs = hasDomainURLs(pkg);
17487        if (!hasDomainURLs) {
17488            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17489                    "No domain URLs, so no need to verify any IntentFilter!");
17490            return;
17491        }
17492
17493        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17494                + " if any IntentFilter from the " + size
17495                + " Activities needs verification ...");
17496
17497        int count = 0;
17498        final String packageName = pkg.packageName;
17499
17500        synchronized (mPackages) {
17501            // If this is a new install and we see that we've already run verification for this
17502            // package, we have nothing to do: it means the state was restored from backup.
17503            if (!replacing) {
17504                IntentFilterVerificationInfo ivi =
17505                        mSettings.getIntentFilterVerificationLPr(packageName);
17506                if (ivi != null) {
17507                    if (DEBUG_DOMAIN_VERIFICATION) {
17508                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17509                                + ivi.getStatusString());
17510                    }
17511                    return;
17512                }
17513            }
17514
17515            // If any filters need to be verified, then all need to be.
17516            boolean needToVerify = false;
17517            for (PackageParser.Activity a : pkg.activities) {
17518                for (ActivityIntentInfo filter : a.intents) {
17519                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17520                        if (DEBUG_DOMAIN_VERIFICATION) {
17521                            Slog.d(TAG,
17522                                    "Intent filter needs verification, so processing all filters");
17523                        }
17524                        needToVerify = true;
17525                        break;
17526                    }
17527                }
17528            }
17529
17530            if (needToVerify) {
17531                final int verificationId = mIntentFilterVerificationToken++;
17532                for (PackageParser.Activity a : pkg.activities) {
17533                    for (ActivityIntentInfo filter : a.intents) {
17534                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17535                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17536                                    "Verification needed for IntentFilter:" + filter.toString());
17537                            mIntentFilterVerifier.addOneIntentFilterVerification(
17538                                    verifierUid, userId, verificationId, filter, packageName);
17539                            count++;
17540                        }
17541                    }
17542                }
17543            }
17544        }
17545
17546        if (count > 0) {
17547            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17548                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17549                    +  " for userId:" + userId);
17550            mIntentFilterVerifier.startVerifications(userId);
17551        } else {
17552            if (DEBUG_DOMAIN_VERIFICATION) {
17553                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17554            }
17555        }
17556    }
17557
17558    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17559        final ComponentName cn  = filter.activity.getComponentName();
17560        final String packageName = cn.getPackageName();
17561
17562        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17563                packageName);
17564        if (ivi == null) {
17565            return true;
17566        }
17567        int status = ivi.getStatus();
17568        switch (status) {
17569            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17570            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17571                return true;
17572
17573            default:
17574                // Nothing to do
17575                return false;
17576        }
17577    }
17578
17579    private static boolean isMultiArch(ApplicationInfo info) {
17580        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17581    }
17582
17583    private static boolean isExternal(PackageParser.Package pkg) {
17584        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17585    }
17586
17587    private static boolean isExternal(PackageSetting ps) {
17588        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17589    }
17590
17591    private static boolean isSystemApp(PackageParser.Package pkg) {
17592        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17593    }
17594
17595    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17596        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17597    }
17598
17599    private static boolean isOemApp(PackageParser.Package pkg) {
17600        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17601    }
17602
17603    private static boolean isVendorApp(PackageParser.Package pkg) {
17604        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
17605    }
17606
17607    private static boolean isProductApp(PackageParser.Package pkg) {
17608        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
17609    }
17610
17611    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17612        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17613    }
17614
17615    private static boolean isSystemApp(PackageSetting ps) {
17616        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17617    }
17618
17619    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17620        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17621    }
17622
17623    private int packageFlagsToInstallFlags(PackageSetting ps) {
17624        int installFlags = 0;
17625        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17626            // This existing package was an external ASEC install when we have
17627            // the external flag without a UUID
17628            installFlags |= PackageManager.INSTALL_EXTERNAL;
17629        }
17630        if (ps.isForwardLocked()) {
17631            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17632        }
17633        return installFlags;
17634    }
17635
17636    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17637        if (isExternal(pkg)) {
17638            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17639                return mSettings.getExternalVersion();
17640            } else {
17641                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17642            }
17643        } else {
17644            return mSettings.getInternalVersion();
17645        }
17646    }
17647
17648    private void deleteTempPackageFiles() {
17649        final FilenameFilter filter = new FilenameFilter() {
17650            public boolean accept(File dir, String name) {
17651                return name.startsWith("vmdl") && name.endsWith(".tmp");
17652            }
17653        };
17654        for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) {
17655            file.delete();
17656        }
17657    }
17658
17659    @Override
17660    public void deletePackageAsUser(String packageName, int versionCode,
17661            IPackageDeleteObserver observer, int userId, int flags) {
17662        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17663                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17664    }
17665
17666    @Override
17667    public void deletePackageVersioned(VersionedPackage versionedPackage,
17668            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17669        final int callingUid = Binder.getCallingUid();
17670        mContext.enforceCallingOrSelfPermission(
17671                android.Manifest.permission.DELETE_PACKAGES, null);
17672        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
17673        Preconditions.checkNotNull(versionedPackage);
17674        Preconditions.checkNotNull(observer);
17675        Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(),
17676                PackageManager.VERSION_CODE_HIGHEST,
17677                Long.MAX_VALUE, "versionCode must be >= -1");
17678
17679        final String packageName = versionedPackage.getPackageName();
17680        final long versionCode = versionedPackage.getLongVersionCode();
17681        final String internalPackageName;
17682        synchronized (mPackages) {
17683            // Normalize package name to handle renamed packages and static libs
17684            internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode);
17685        }
17686
17687        final int uid = Binder.getCallingUid();
17688        if (!isOrphaned(internalPackageName)
17689                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17690            try {
17691                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17692                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17693                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17694                observer.onUserActionRequired(intent);
17695            } catch (RemoteException re) {
17696            }
17697            return;
17698        }
17699        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17700        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17701        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17702            mContext.enforceCallingOrSelfPermission(
17703                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17704                    "deletePackage for user " + userId);
17705        }
17706
17707        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17708            try {
17709                observer.onPackageDeleted(packageName,
17710                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17711            } catch (RemoteException re) {
17712            }
17713            return;
17714        }
17715
17716        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17717            try {
17718                observer.onPackageDeleted(packageName,
17719                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17720            } catch (RemoteException re) {
17721            }
17722            return;
17723        }
17724
17725        if (DEBUG_REMOVE) {
17726            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17727                    + " deleteAllUsers: " + deleteAllUsers + " version="
17728                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17729                    ? "VERSION_CODE_HIGHEST" : versionCode));
17730        }
17731        // Queue up an async operation since the package deletion may take a little while.
17732        mHandler.post(new Runnable() {
17733            public void run() {
17734                mHandler.removeCallbacks(this);
17735                int returnCode;
17736                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
17737                boolean doDeletePackage = true;
17738                if (ps != null) {
17739                    final boolean targetIsInstantApp =
17740                            ps.getInstantApp(UserHandle.getUserId(callingUid));
17741                    doDeletePackage = !targetIsInstantApp
17742                            || canViewInstantApps;
17743                }
17744                if (doDeletePackage) {
17745                    if (!deleteAllUsers) {
17746                        returnCode = deletePackageX(internalPackageName, versionCode,
17747                                userId, deleteFlags);
17748                    } else {
17749                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
17750                                internalPackageName, users);
17751                        // If nobody is blocking uninstall, proceed with delete for all users
17752                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17753                            returnCode = deletePackageX(internalPackageName, versionCode,
17754                                    userId, deleteFlags);
17755                        } else {
17756                            // Otherwise uninstall individually for users with blockUninstalls=false
17757                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17758                            for (int userId : users) {
17759                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17760                                    returnCode = deletePackageX(internalPackageName, versionCode,
17761                                            userId, userFlags);
17762                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17763                                        Slog.w(TAG, "Package delete failed for user " + userId
17764                                                + ", returnCode " + returnCode);
17765                                    }
17766                                }
17767                            }
17768                            // The app has only been marked uninstalled for certain users.
17769                            // We still need to report that delete was blocked
17770                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17771                        }
17772                    }
17773                } else {
17774                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17775                }
17776                try {
17777                    observer.onPackageDeleted(packageName, returnCode, null);
17778                } catch (RemoteException e) {
17779                    Log.i(TAG, "Observer no longer exists.");
17780                } //end catch
17781            } //end run
17782        });
17783    }
17784
17785    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17786        if (pkg.staticSharedLibName != null) {
17787            return pkg.manifestPackageName;
17788        }
17789        return pkg.packageName;
17790    }
17791
17792    private String resolveInternalPackageNameLPr(String packageName, long versionCode) {
17793        // Handle renamed packages
17794        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17795        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17796
17797        // Is this a static library?
17798        LongSparseArray<SharedLibraryEntry> versionedLib =
17799                mStaticLibsByDeclaringPackage.get(packageName);
17800        if (versionedLib == null || versionedLib.size() <= 0) {
17801            return packageName;
17802        }
17803
17804        // Figure out which lib versions the caller can see
17805        LongSparseLongArray versionsCallerCanSee = null;
17806        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17807        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17808                && callingAppId != Process.ROOT_UID) {
17809            versionsCallerCanSee = new LongSparseLongArray();
17810            String libName = versionedLib.valueAt(0).info.getName();
17811            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17812            if (uidPackages != null) {
17813                for (String uidPackage : uidPackages) {
17814                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17815                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17816                    if (libIdx >= 0) {
17817                        final long libVersion = ps.usesStaticLibrariesVersions[libIdx];
17818                        versionsCallerCanSee.append(libVersion, libVersion);
17819                    }
17820                }
17821            }
17822        }
17823
17824        // Caller can see nothing - done
17825        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17826            return packageName;
17827        }
17828
17829        // Find the version the caller can see and the app version code
17830        SharedLibraryEntry highestVersion = null;
17831        final int versionCount = versionedLib.size();
17832        for (int i = 0; i < versionCount; i++) {
17833            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17834            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17835                    libEntry.info.getLongVersion()) < 0) {
17836                continue;
17837            }
17838            final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode();
17839            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17840                if (libVersionCode == versionCode) {
17841                    return libEntry.apk;
17842                }
17843            } else if (highestVersion == null) {
17844                highestVersion = libEntry;
17845            } else if (libVersionCode  > highestVersion.info
17846                    .getDeclaringPackage().getLongVersionCode()) {
17847                highestVersion = libEntry;
17848            }
17849        }
17850
17851        if (highestVersion != null) {
17852            return highestVersion.apk;
17853        }
17854
17855        return packageName;
17856    }
17857
17858    boolean isCallerVerifier(int callingUid) {
17859        final int callingUserId = UserHandle.getUserId(callingUid);
17860        return mRequiredVerifierPackage != null &&
17861                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
17862    }
17863
17864    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17865        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17866              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17867            return true;
17868        }
17869        final int callingUserId = UserHandle.getUserId(callingUid);
17870        // If the caller installed the pkgName, then allow it to silently uninstall.
17871        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17872            return true;
17873        }
17874
17875        // Allow package verifier to silently uninstall.
17876        if (mRequiredVerifierPackage != null &&
17877                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17878            return true;
17879        }
17880
17881        // Allow package uninstaller to silently uninstall.
17882        if (mRequiredUninstallerPackage != null &&
17883                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17884            return true;
17885        }
17886
17887        // Allow storage manager to silently uninstall.
17888        if (mStorageManagerPackage != null &&
17889                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17890            return true;
17891        }
17892
17893        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
17894        // uninstall for device owner provisioning.
17895        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
17896                == PERMISSION_GRANTED) {
17897            return true;
17898        }
17899
17900        return false;
17901    }
17902
17903    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17904        int[] result = EMPTY_INT_ARRAY;
17905        for (int userId : userIds) {
17906            if (getBlockUninstallForUser(packageName, userId)) {
17907                result = ArrayUtils.appendInt(result, userId);
17908            }
17909        }
17910        return result;
17911    }
17912
17913    @Override
17914    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17915        final int callingUid = Binder.getCallingUid();
17916        if (getInstantAppPackageName(callingUid) != null
17917                && !isCallerSameApp(packageName, callingUid)) {
17918            return false;
17919        }
17920        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17921    }
17922
17923    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17924        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17925                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17926        try {
17927            if (dpm != null) {
17928                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17929                        /* callingUserOnly =*/ false);
17930                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17931                        : deviceOwnerComponentName.getPackageName();
17932                // Does the package contains the device owner?
17933                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17934                // this check is probably not needed, since DO should be registered as a device
17935                // admin on some user too. (Original bug for this: b/17657954)
17936                if (packageName.equals(deviceOwnerPackageName)) {
17937                    return true;
17938                }
17939                // Does it contain a device admin for any user?
17940                int[] users;
17941                if (userId == UserHandle.USER_ALL) {
17942                    users = sUserManager.getUserIds();
17943                } else {
17944                    users = new int[]{userId};
17945                }
17946                for (int i = 0; i < users.length; ++i) {
17947                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17948                        return true;
17949                    }
17950                }
17951            }
17952        } catch (RemoteException e) {
17953        }
17954        return false;
17955    }
17956
17957    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17958        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17959    }
17960
17961    /**
17962     *  This method is an internal method that could be get invoked either
17963     *  to delete an installed package or to clean up a failed installation.
17964     *  After deleting an installed package, a broadcast is sent to notify any
17965     *  listeners that the package has been removed. For cleaning up a failed
17966     *  installation, the broadcast is not necessary since the package's
17967     *  installation wouldn't have sent the initial broadcast either
17968     *  The key steps in deleting a package are
17969     *  deleting the package information in internal structures like mPackages,
17970     *  deleting the packages base directories through installd
17971     *  updating mSettings to reflect current status
17972     *  persisting settings for later use
17973     *  sending a broadcast if necessary
17974     */
17975    int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) {
17976        final PackageRemovedInfo info = new PackageRemovedInfo(this);
17977        final boolean res;
17978
17979        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17980                ? UserHandle.USER_ALL : userId;
17981
17982        if (isPackageDeviceAdmin(packageName, removeUser)) {
17983            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17984            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17985        }
17986
17987        PackageSetting uninstalledPs = null;
17988        PackageParser.Package pkg = null;
17989
17990        // for the uninstall-updates case and restricted profiles, remember the per-
17991        // user handle installed state
17992        int[] allUsers;
17993        synchronized (mPackages) {
17994            uninstalledPs = mSettings.mPackages.get(packageName);
17995            if (uninstalledPs == null) {
17996                Slog.w(TAG, "Not removing non-existent package " + packageName);
17997                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17998            }
17999
18000            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18001                    && uninstalledPs.versionCode != versionCode) {
18002                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18003                        + uninstalledPs.versionCode + " != " + versionCode);
18004                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18005            }
18006
18007            // Static shared libs can be declared by any package, so let us not
18008            // allow removing a package if it provides a lib others depend on.
18009            pkg = mPackages.get(packageName);
18010
18011            allUsers = sUserManager.getUserIds();
18012
18013            if (pkg != null && pkg.staticSharedLibName != null) {
18014                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18015                        pkg.staticSharedLibVersion);
18016                if (libEntry != null) {
18017                    for (int currUserId : allUsers) {
18018                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18019                            continue;
18020                        }
18021                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18022                                libEntry.info, 0, currUserId);
18023                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18024                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18025                                    + " hosting lib " + libEntry.info.getName() + " version "
18026                                    + libEntry.info.getLongVersion() + " used by " + libClientPackages
18027                                    + " for user " + currUserId);
18028                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18029                        }
18030                    }
18031                }
18032            }
18033
18034            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18035        }
18036
18037        final int freezeUser;
18038        if (isUpdatedSystemApp(uninstalledPs)
18039                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18040            // We're downgrading a system app, which will apply to all users, so
18041            // freeze them all during the downgrade
18042            freezeUser = UserHandle.USER_ALL;
18043        } else {
18044            freezeUser = removeUser;
18045        }
18046
18047        synchronized (mInstallLock) {
18048            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18049            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18050                    deleteFlags, "deletePackageX")) {
18051                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18052                        deleteFlags | PackageManager.DELETE_CHATTY, info, true, null);
18053            }
18054            synchronized (mPackages) {
18055                if (res) {
18056                    if (pkg != null) {
18057                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18058                    }
18059                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18060                    updateInstantAppInstallerLocked(packageName);
18061                }
18062            }
18063        }
18064
18065        if (res) {
18066            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18067            info.sendPackageRemovedBroadcasts(killApp);
18068            info.sendSystemPackageUpdatedBroadcasts();
18069            info.sendSystemPackageAppearedBroadcasts();
18070        }
18071        // Force a gc here.
18072        Runtime.getRuntime().gc();
18073        // Delete the resources here after sending the broadcast to let
18074        // other processes clean up before deleting resources.
18075        if (info.args != null) {
18076            synchronized (mInstallLock) {
18077                info.args.doPostDeleteLI(true);
18078            }
18079        }
18080
18081        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18082    }
18083
18084    static class PackageRemovedInfo {
18085        final PackageSender packageSender;
18086        String removedPackage;
18087        String installerPackageName;
18088        int uid = -1;
18089        int removedAppId = -1;
18090        int[] origUsers;
18091        int[] removedUsers = null;
18092        int[] broadcastUsers = null;
18093        int[] instantUserIds = null;
18094        SparseArray<Integer> installReasons;
18095        boolean isRemovedPackageSystemUpdate = false;
18096        boolean isUpdate;
18097        boolean dataRemoved;
18098        boolean removedForAllUsers;
18099        boolean isStaticSharedLib;
18100        // Clean up resources deleted packages.
18101        InstallArgs args = null;
18102        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18103        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18104
18105        PackageRemovedInfo(PackageSender packageSender) {
18106            this.packageSender = packageSender;
18107        }
18108
18109        void sendPackageRemovedBroadcasts(boolean killApp) {
18110            sendPackageRemovedBroadcastInternal(killApp);
18111            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18112            for (int i = 0; i < childCount; i++) {
18113                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18114                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18115            }
18116        }
18117
18118        void sendSystemPackageUpdatedBroadcasts() {
18119            if (isRemovedPackageSystemUpdate) {
18120                sendSystemPackageUpdatedBroadcastsInternal();
18121                final int childCount = (removedChildPackages != null)
18122                        ? removedChildPackages.size() : 0;
18123                for (int i = 0; i < childCount; i++) {
18124                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18125                    if (childInfo.isRemovedPackageSystemUpdate) {
18126                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18127                    }
18128                }
18129            }
18130        }
18131
18132        void sendSystemPackageAppearedBroadcasts() {
18133            final int packageCount = (appearedChildPackages != null)
18134                    ? appearedChildPackages.size() : 0;
18135            for (int i = 0; i < packageCount; i++) {
18136                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18137                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18138                    true /*sendBootCompleted*/, false /*startReceiver*/,
18139                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null);
18140            }
18141        }
18142
18143        private void sendSystemPackageUpdatedBroadcastsInternal() {
18144            Bundle extras = new Bundle(2);
18145            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18146            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18147            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18148                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18149            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18150                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18151            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18152                null, null, 0, removedPackage, null, null, null);
18153            if (installerPackageName != null) {
18154                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18155                        removedPackage, extras, 0 /*flags*/,
18156                        installerPackageName, null, null, null);
18157                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18158                        removedPackage, extras, 0 /*flags*/,
18159                        installerPackageName, null, null, null);
18160            }
18161        }
18162
18163        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18164            // Don't send static shared library removal broadcasts as these
18165            // libs are visible only the the apps that depend on them an one
18166            // cannot remove the library if it has a dependency.
18167            if (isStaticSharedLib) {
18168                return;
18169            }
18170            Bundle extras = new Bundle(2);
18171            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18172            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18173            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18174            if (isUpdate || isRemovedPackageSystemUpdate) {
18175                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18176            }
18177            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18178            if (removedPackage != null) {
18179                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18180                    removedPackage, extras, 0, null /*targetPackage*/, null,
18181                    broadcastUsers, instantUserIds);
18182                if (installerPackageName != null) {
18183                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18184                            removedPackage, extras, 0 /*flags*/,
18185                            installerPackageName, null, broadcastUsers, instantUserIds);
18186                }
18187                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18188                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18189                        removedPackage, extras,
18190                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18191                        null, null, broadcastUsers, instantUserIds);
18192                    packageSender.notifyPackageRemoved(removedPackage);
18193                }
18194            }
18195            if (removedAppId >= 0) {
18196                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
18197                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18198                    null, null, broadcastUsers, instantUserIds);
18199            }
18200        }
18201
18202        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18203            removedUsers = userIds;
18204            if (removedUsers == null) {
18205                broadcastUsers = null;
18206                return;
18207            }
18208
18209            broadcastUsers = EMPTY_INT_ARRAY;
18210            instantUserIds = EMPTY_INT_ARRAY;
18211            for (int i = userIds.length - 1; i >= 0; --i) {
18212                final int userId = userIds[i];
18213                if (deletedPackageSetting.getInstantApp(userId)) {
18214                    instantUserIds = ArrayUtils.appendInt(instantUserIds, userId);
18215                } else {
18216                    broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18217                }
18218            }
18219        }
18220    }
18221
18222    /*
18223     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18224     * flag is not set, the data directory is removed as well.
18225     * make sure this flag is set for partially installed apps. If not its meaningless to
18226     * delete a partially installed application.
18227     */
18228    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18229            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18230        String packageName = ps.name;
18231        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18232        // Retrieve object to delete permissions for shared user later on
18233        final PackageParser.Package deletedPkg;
18234        final PackageSetting deletedPs;
18235        // reader
18236        synchronized (mPackages) {
18237            deletedPkg = mPackages.get(packageName);
18238            deletedPs = mSettings.mPackages.get(packageName);
18239            if (outInfo != null) {
18240                outInfo.removedPackage = packageName;
18241                outInfo.installerPackageName = ps.installerPackageName;
18242                outInfo.isStaticSharedLib = deletedPkg != null
18243                        && deletedPkg.staticSharedLibName != null;
18244                outInfo.populateUsers(deletedPs == null ? null
18245                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18246            }
18247        }
18248
18249        removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0);
18250
18251        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18252            final PackageParser.Package resolvedPkg;
18253            if (deletedPkg != null) {
18254                resolvedPkg = deletedPkg;
18255            } else {
18256                // We don't have a parsed package when it lives on an ejected
18257                // adopted storage device, so fake something together
18258                resolvedPkg = new PackageParser.Package(ps.name);
18259                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18260            }
18261            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18262                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18263            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18264            if (outInfo != null) {
18265                outInfo.dataRemoved = true;
18266            }
18267            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18268        }
18269
18270        int removedAppId = -1;
18271
18272        // writer
18273        synchronized (mPackages) {
18274            boolean installedStateChanged = false;
18275            if (deletedPs != null) {
18276                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18277                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18278                    clearDefaultBrowserIfNeeded(packageName);
18279                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18280                    removedAppId = mSettings.removePackageLPw(packageName);
18281                    if (outInfo != null) {
18282                        outInfo.removedAppId = removedAppId;
18283                    }
18284                    mPermissionManager.updatePermissions(
18285                            deletedPs.name, null, false, mPackages.values(), mPermissionCallback);
18286                    if (deletedPs.sharedUser != null) {
18287                        // Remove permissions associated with package. Since runtime
18288                        // permissions are per user we have to kill the removed package
18289                        // or packages running under the shared user of the removed
18290                        // package if revoking the permissions requested only by the removed
18291                        // package is successful and this causes a change in gids.
18292                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18293                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18294                                    userId);
18295                            if (userIdToKill == UserHandle.USER_ALL
18296                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18297                                // If gids changed for this user, kill all affected packages.
18298                                mHandler.post(new Runnable() {
18299                                    @Override
18300                                    public void run() {
18301                                        // This has to happen with no lock held.
18302                                        killApplication(deletedPs.name, deletedPs.appId,
18303                                                KILL_APP_REASON_GIDS_CHANGED);
18304                                    }
18305                                });
18306                                break;
18307                            }
18308                        }
18309                    }
18310                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18311                }
18312                // make sure to preserve per-user disabled state if this removal was just
18313                // a downgrade of a system app to the factory package
18314                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18315                    if (DEBUG_REMOVE) {
18316                        Slog.d(TAG, "Propagating install state across downgrade");
18317                    }
18318                    for (int userId : allUserHandles) {
18319                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18320                        if (DEBUG_REMOVE) {
18321                            Slog.d(TAG, "    user " + userId + " => " + installed);
18322                        }
18323                        if (installed != ps.getInstalled(userId)) {
18324                            installedStateChanged = true;
18325                        }
18326                        ps.setInstalled(installed, userId);
18327                    }
18328                }
18329            }
18330            // can downgrade to reader
18331            if (writeSettings) {
18332                // Save settings now
18333                mSettings.writeLPr();
18334            }
18335            if (installedStateChanged) {
18336                mSettings.writeKernelMappingLPr(ps);
18337            }
18338        }
18339        if (removedAppId != -1) {
18340            // A user ID was deleted here. Go through all users and remove it
18341            // from KeyStore.
18342            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18343        }
18344    }
18345
18346    static boolean locationIsPrivileged(String path) {
18347        try {
18348            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
18349            final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
18350            final File privilegedOdmAppDir = new File(Environment.getOdmDirectory(), "priv-app");
18351            final File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
18352            return path.startsWith(privilegedAppDir.getCanonicalPath())
18353                    || path.startsWith(privilegedVendorAppDir.getCanonicalPath())
18354                    || path.startsWith(privilegedOdmAppDir.getCanonicalPath())
18355                    || path.startsWith(privilegedProductAppDir.getCanonicalPath());
18356        } catch (IOException e) {
18357            Slog.e(TAG, "Unable to access code path " + path);
18358        }
18359        return false;
18360    }
18361
18362    static boolean locationIsOem(String path) {
18363        try {
18364            return path.startsWith(Environment.getOemDirectory().getCanonicalPath());
18365        } catch (IOException e) {
18366            Slog.e(TAG, "Unable to access code path " + path);
18367        }
18368        return false;
18369    }
18370
18371    static boolean locationIsVendor(String path) {
18372        try {
18373            return path.startsWith(Environment.getVendorDirectory().getCanonicalPath())
18374                    || path.startsWith(Environment.getOdmDirectory().getCanonicalPath());
18375        } catch (IOException e) {
18376            Slog.e(TAG, "Unable to access code path " + path);
18377        }
18378        return false;
18379    }
18380
18381    static boolean locationIsProduct(String path) {
18382        try {
18383            return path.startsWith(Environment.getProductDirectory().getCanonicalPath());
18384        } catch (IOException e) {
18385            Slog.e(TAG, "Unable to access code path " + path);
18386        }
18387        return false;
18388    }
18389
18390    /*
18391     * Tries to delete system package.
18392     */
18393    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18394            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18395            boolean writeSettings) {
18396        if (deletedPs.parentPackageName != null) {
18397            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18398            return false;
18399        }
18400
18401        final boolean applyUserRestrictions
18402                = (allUserHandles != null) && (outInfo.origUsers != null);
18403        final PackageSetting disabledPs;
18404        // Confirm if the system package has been updated
18405        // An updated system app can be deleted. This will also have to restore
18406        // the system pkg from system partition
18407        // reader
18408        synchronized (mPackages) {
18409            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18410        }
18411
18412        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18413                + " disabledPs=" + disabledPs);
18414
18415        if (disabledPs == null) {
18416            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18417            return false;
18418        } else if (DEBUG_REMOVE) {
18419            Slog.d(TAG, "Deleting system pkg from data partition");
18420        }
18421
18422        if (DEBUG_REMOVE) {
18423            if (applyUserRestrictions) {
18424                Slog.d(TAG, "Remembering install states:");
18425                for (int userId : allUserHandles) {
18426                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18427                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18428                }
18429            }
18430        }
18431
18432        // Delete the updated package
18433        outInfo.isRemovedPackageSystemUpdate = true;
18434        if (outInfo.removedChildPackages != null) {
18435            final int childCount = (deletedPs.childPackageNames != null)
18436                    ? deletedPs.childPackageNames.size() : 0;
18437            for (int i = 0; i < childCount; i++) {
18438                String childPackageName = deletedPs.childPackageNames.get(i);
18439                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18440                        .contains(childPackageName)) {
18441                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18442                            childPackageName);
18443                    if (childInfo != null) {
18444                        childInfo.isRemovedPackageSystemUpdate = true;
18445                    }
18446                }
18447            }
18448        }
18449
18450        if (disabledPs.versionCode < deletedPs.versionCode) {
18451            // Delete data for downgrades
18452            flags &= ~PackageManager.DELETE_KEEP_DATA;
18453        } else {
18454            // Preserve data by setting flag
18455            flags |= PackageManager.DELETE_KEEP_DATA;
18456        }
18457
18458        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18459                outInfo, writeSettings, disabledPs.pkg);
18460        if (!ret) {
18461            return false;
18462        }
18463
18464        // writer
18465        synchronized (mPackages) {
18466            // NOTE: The system package always needs to be enabled; even if it's for
18467            // a compressed stub. If we don't, installing the system package fails
18468            // during scan [scanning checks the disabled packages]. We will reverse
18469            // this later, after we've "installed" the stub.
18470            // Reinstate the old system package
18471            enableSystemPackageLPw(disabledPs.pkg);
18472            // Remove any native libraries from the upgraded package.
18473            removeNativeBinariesLI(deletedPs);
18474        }
18475
18476        // Install the system package
18477        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18478        try {
18479            installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles,
18480                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
18481        } catch (PackageManagerException e) {
18482            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18483                    + e.getMessage());
18484            return false;
18485        } finally {
18486            if (disabledPs.pkg.isStub) {
18487                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
18488            }
18489        }
18490        return true;
18491    }
18492
18493    /**
18494     * Installs a package that's already on the system partition.
18495     */
18496    private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString,
18497            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
18498            @Nullable PermissionsState origPermissionState, boolean writeSettings)
18499                    throws PackageManagerException {
18500        @ParseFlags int parseFlags =
18501                mDefParseFlags
18502                | PackageParser.PARSE_MUST_BE_APK
18503                | PackageParser.PARSE_IS_SYSTEM_DIR;
18504        @ScanFlags int scanFlags = SCAN_AS_SYSTEM;
18505        if (isPrivileged || locationIsPrivileged(codePathString)) {
18506            scanFlags |= SCAN_AS_PRIVILEGED;
18507        }
18508        if (locationIsOem(codePathString)) {
18509            scanFlags |= SCAN_AS_OEM;
18510        }
18511        if (locationIsVendor(codePathString)) {
18512            scanFlags |= SCAN_AS_VENDOR;
18513        }
18514        if (locationIsProduct(codePathString)) {
18515            scanFlags |= SCAN_AS_PRODUCT;
18516        }
18517
18518        final File codePath = new File(codePathString);
18519        final PackageParser.Package pkg =
18520                scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null);
18521
18522        try {
18523            // update shared libraries for the newly re-installed system package
18524            updateSharedLibrariesLPr(pkg, null);
18525        } catch (PackageManagerException e) {
18526            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18527        }
18528
18529        prepareAppDataAfterInstallLIF(pkg);
18530
18531        // writer
18532        synchronized (mPackages) {
18533            PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
18534
18535            // Propagate the permissions state as we do not want to drop on the floor
18536            // runtime permissions. The update permissions method below will take
18537            // care of removing obsolete permissions and grant install permissions.
18538            if (origPermissionState != null) {
18539                ps.getPermissionsState().copyFrom(origPermissionState);
18540            }
18541            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
18542                    mPermissionCallback);
18543
18544            final boolean applyUserRestrictions
18545                    = (allUserHandles != null) && (origUserHandles != null);
18546            if (applyUserRestrictions) {
18547                boolean installedStateChanged = false;
18548                if (DEBUG_REMOVE) {
18549                    Slog.d(TAG, "Propagating install state across reinstall");
18550                }
18551                for (int userId : allUserHandles) {
18552                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
18553                    if (DEBUG_REMOVE) {
18554                        Slog.d(TAG, "    user " + userId + " => " + installed);
18555                    }
18556                    if (installed != ps.getInstalled(userId)) {
18557                        installedStateChanged = true;
18558                    }
18559                    ps.setInstalled(installed, userId);
18560
18561                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18562                }
18563                // Regardless of writeSettings we need to ensure that this restriction
18564                // state propagation is persisted
18565                mSettings.writeAllUsersPackageRestrictionsLPr();
18566                if (installedStateChanged) {
18567                    mSettings.writeKernelMappingLPr(ps);
18568                }
18569            }
18570            // can downgrade to reader here
18571            if (writeSettings) {
18572                mSettings.writeLPr();
18573            }
18574        }
18575        return pkg;
18576    }
18577
18578    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18579            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18580            PackageRemovedInfo outInfo, boolean writeSettings,
18581            PackageParser.Package replacingPackage) {
18582        synchronized (mPackages) {
18583            if (outInfo != null) {
18584                outInfo.uid = ps.appId;
18585            }
18586
18587            if (outInfo != null && outInfo.removedChildPackages != null) {
18588                final int childCount = (ps.childPackageNames != null)
18589                        ? ps.childPackageNames.size() : 0;
18590                for (int i = 0; i < childCount; i++) {
18591                    String childPackageName = ps.childPackageNames.get(i);
18592                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18593                    if (childPs == null) {
18594                        return false;
18595                    }
18596                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18597                            childPackageName);
18598                    if (childInfo != null) {
18599                        childInfo.uid = childPs.appId;
18600                    }
18601                }
18602            }
18603        }
18604
18605        // Delete package data from internal structures and also remove data if flag is set
18606        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18607
18608        // Delete the child packages data
18609        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18610        for (int i = 0; i < childCount; i++) {
18611            PackageSetting childPs;
18612            synchronized (mPackages) {
18613                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18614            }
18615            if (childPs != null) {
18616                PackageRemovedInfo childOutInfo = (outInfo != null
18617                        && outInfo.removedChildPackages != null)
18618                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18619                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18620                        && (replacingPackage != null
18621                        && !replacingPackage.hasChildPackage(childPs.name))
18622                        ? flags & ~DELETE_KEEP_DATA : flags;
18623                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18624                        deleteFlags, writeSettings);
18625            }
18626        }
18627
18628        // Delete application code and resources only for parent packages
18629        if (ps.parentPackageName == null) {
18630            if (deleteCodeAndResources && (outInfo != null)) {
18631                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18632                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18633                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18634            }
18635        }
18636
18637        return true;
18638    }
18639
18640    @Override
18641    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18642            int userId) {
18643        mContext.enforceCallingOrSelfPermission(
18644                android.Manifest.permission.DELETE_PACKAGES, null);
18645        synchronized (mPackages) {
18646            // Cannot block uninstall of static shared libs as they are
18647            // considered a part of the using app (emulating static linking).
18648            // Also static libs are installed always on internal storage.
18649            PackageParser.Package pkg = mPackages.get(packageName);
18650            if (pkg != null && pkg.staticSharedLibName != null) {
18651                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18652                        + " providing static shared library: " + pkg.staticSharedLibName);
18653                return false;
18654            }
18655            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18656            mSettings.writePackageRestrictionsLPr(userId);
18657        }
18658        return true;
18659    }
18660
18661    @Override
18662    public boolean getBlockUninstallForUser(String packageName, int userId) {
18663        synchronized (mPackages) {
18664            final PackageSetting ps = mSettings.mPackages.get(packageName);
18665            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
18666                return false;
18667            }
18668            return mSettings.getBlockUninstallLPr(userId, packageName);
18669        }
18670    }
18671
18672    @Override
18673    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18674        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
18675        synchronized (mPackages) {
18676            PackageSetting ps = mSettings.mPackages.get(packageName);
18677            if (ps == null) {
18678                Log.w(TAG, "Package doesn't exist: " + packageName);
18679                return false;
18680            }
18681            if (systemUserApp) {
18682                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18683            } else {
18684                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18685            }
18686            mSettings.writeLPr();
18687        }
18688        return true;
18689    }
18690
18691    /*
18692     * This method handles package deletion in general
18693     */
18694    private boolean deletePackageLIF(String packageName, UserHandle user,
18695            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18696            PackageRemovedInfo outInfo, boolean writeSettings,
18697            PackageParser.Package replacingPackage) {
18698        if (packageName == null) {
18699            Slog.w(TAG, "Attempt to delete null packageName.");
18700            return false;
18701        }
18702
18703        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18704
18705        PackageSetting ps;
18706        synchronized (mPackages) {
18707            ps = mSettings.mPackages.get(packageName);
18708            if (ps == null) {
18709                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18710                return false;
18711            }
18712
18713            if (ps.parentPackageName != null && (!isSystemApp(ps)
18714                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18715                if (DEBUG_REMOVE) {
18716                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18717                            + ((user == null) ? UserHandle.USER_ALL : user));
18718                }
18719                final int removedUserId = (user != null) ? user.getIdentifier()
18720                        : UserHandle.USER_ALL;
18721
18722                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18723                    return false;
18724                }
18725                markPackageUninstalledForUserLPw(ps, user);
18726                scheduleWritePackageRestrictionsLocked(user);
18727                return true;
18728            }
18729        }
18730
18731        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
18732        if (ps.getPermissionsState().hasPermission(Manifest.permission.SUSPEND_APPS, userId)) {
18733            onSuspendingPackageRemoved(packageName, userId);
18734        }
18735
18736
18737        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18738                && user.getIdentifier() != UserHandle.USER_ALL)) {
18739            // The caller is asking that the package only be deleted for a single
18740            // user.  To do this, we just mark its uninstalled state and delete
18741            // its data. If this is a system app, we only allow this to happen if
18742            // they have set the special DELETE_SYSTEM_APP which requests different
18743            // semantics than normal for uninstalling system apps.
18744            markPackageUninstalledForUserLPw(ps, user);
18745
18746            if (!isSystemApp(ps)) {
18747                // Do not uninstall the APK if an app should be cached
18748                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18749                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18750                    // Other user still have this package installed, so all
18751                    // we need to do is clear this user's data and save that
18752                    // it is uninstalled.
18753                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18754                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18755                        return false;
18756                    }
18757                    scheduleWritePackageRestrictionsLocked(user);
18758                    return true;
18759                } else {
18760                    // We need to set it back to 'installed' so the uninstall
18761                    // broadcasts will be sent correctly.
18762                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18763                    ps.setInstalled(true, user.getIdentifier());
18764                    mSettings.writeKernelMappingLPr(ps);
18765                }
18766            } else {
18767                // This is a system app, so we assume that the
18768                // other users still have this package installed, so all
18769                // we need to do is clear this user's data and save that
18770                // it is uninstalled.
18771                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18772                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18773                    return false;
18774                }
18775                scheduleWritePackageRestrictionsLocked(user);
18776                return true;
18777            }
18778        }
18779
18780        // If we are deleting a composite package for all users, keep track
18781        // of result for each child.
18782        if (ps.childPackageNames != null && outInfo != null) {
18783            synchronized (mPackages) {
18784                final int childCount = ps.childPackageNames.size();
18785                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18786                for (int i = 0; i < childCount; i++) {
18787                    String childPackageName = ps.childPackageNames.get(i);
18788                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18789                    childInfo.removedPackage = childPackageName;
18790                    childInfo.installerPackageName = ps.installerPackageName;
18791                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18792                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18793                    if (childPs != null) {
18794                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18795                    }
18796                }
18797            }
18798        }
18799
18800        boolean ret = false;
18801        if (isSystemApp(ps)) {
18802            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18803            // When an updated system application is deleted we delete the existing resources
18804            // as well and fall back to existing code in system partition
18805            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18806        } else {
18807            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18808            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18809                    outInfo, writeSettings, replacingPackage);
18810        }
18811
18812        // Take a note whether we deleted the package for all users
18813        if (outInfo != null) {
18814            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18815            if (outInfo.removedChildPackages != null) {
18816                synchronized (mPackages) {
18817                    final int childCount = outInfo.removedChildPackages.size();
18818                    for (int i = 0; i < childCount; i++) {
18819                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18820                        if (childInfo != null) {
18821                            childInfo.removedForAllUsers = mPackages.get(
18822                                    childInfo.removedPackage) == null;
18823                        }
18824                    }
18825                }
18826            }
18827            // If we uninstalled an update to a system app there may be some
18828            // child packages that appeared as they are declared in the system
18829            // app but were not declared in the update.
18830            if (isSystemApp(ps)) {
18831                synchronized (mPackages) {
18832                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18833                    final int childCount = (updatedPs.childPackageNames != null)
18834                            ? updatedPs.childPackageNames.size() : 0;
18835                    for (int i = 0; i < childCount; i++) {
18836                        String childPackageName = updatedPs.childPackageNames.get(i);
18837                        if (outInfo.removedChildPackages == null
18838                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18839                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18840                            if (childPs == null) {
18841                                continue;
18842                            }
18843                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18844                            installRes.name = childPackageName;
18845                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18846                            installRes.pkg = mPackages.get(childPackageName);
18847                            installRes.uid = childPs.pkg.applicationInfo.uid;
18848                            if (outInfo.appearedChildPackages == null) {
18849                                outInfo.appearedChildPackages = new ArrayMap<>();
18850                            }
18851                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18852                        }
18853                    }
18854                }
18855            }
18856        }
18857
18858        return ret;
18859    }
18860
18861    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18862        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18863                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18864        for (int nextUserId : userIds) {
18865            if (DEBUG_REMOVE) {
18866                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18867            }
18868            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18869                    false /*installed*/,
18870                    true /*stopped*/,
18871                    true /*notLaunched*/,
18872                    false /*hidden*/,
18873                    false /*suspended*/,
18874                    null, /*suspendingPackage*/
18875                    null, /*suspendedAppExtras*/
18876                    null, /*suspendedLauncherExtras*/
18877                    false /*instantApp*/,
18878                    false /*virtualPreload*/,
18879                    null /*lastDisableAppCaller*/,
18880                    null /*enabledComponents*/,
18881                    null /*disabledComponents*/,
18882                    ps.readUserState(nextUserId).domainVerificationStatus,
18883                    0, PackageManager.INSTALL_REASON_UNKNOWN,
18884                    null /*harmfulAppWarning*/);
18885        }
18886        mSettings.writeKernelMappingLPr(ps);
18887    }
18888
18889    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18890            PackageRemovedInfo outInfo) {
18891        final PackageParser.Package pkg;
18892        synchronized (mPackages) {
18893            pkg = mPackages.get(ps.name);
18894        }
18895
18896        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18897                : new int[] {userId};
18898        for (int nextUserId : userIds) {
18899            if (DEBUG_REMOVE) {
18900                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18901                        + nextUserId);
18902            }
18903
18904            destroyAppDataLIF(pkg, userId,
18905                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18906            destroyAppProfilesLIF(pkg, userId);
18907            clearDefaultBrowserIfNeededForUser(ps.name, userId);
18908            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18909            schedulePackageCleaning(ps.name, nextUserId, false);
18910            synchronized (mPackages) {
18911                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18912                    scheduleWritePackageRestrictionsLocked(nextUserId);
18913                }
18914                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18915            }
18916        }
18917
18918        if (outInfo != null) {
18919            outInfo.removedPackage = ps.name;
18920            outInfo.installerPackageName = ps.installerPackageName;
18921            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18922            outInfo.removedAppId = ps.appId;
18923            outInfo.removedUsers = userIds;
18924            outInfo.broadcastUsers = userIds;
18925        }
18926
18927        return true;
18928    }
18929
18930    private static final class ClearStorageConnection implements ServiceConnection {
18931        IMediaContainerService mContainerService;
18932
18933        @Override
18934        public void onServiceConnected(ComponentName name, IBinder service) {
18935            synchronized (this) {
18936                mContainerService = IMediaContainerService.Stub
18937                        .asInterface(Binder.allowBlocking(service));
18938                notifyAll();
18939            }
18940        }
18941
18942        @Override
18943        public void onServiceDisconnected(ComponentName name) {
18944        }
18945    }
18946
18947    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18948        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18949
18950        final boolean mounted;
18951        if (Environment.isExternalStorageEmulated()) {
18952            mounted = true;
18953        } else {
18954            final String status = Environment.getExternalStorageState();
18955
18956            mounted = status.equals(Environment.MEDIA_MOUNTED)
18957                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18958        }
18959
18960        if (!mounted) {
18961            return;
18962        }
18963
18964        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18965        int[] users;
18966        if (userId == UserHandle.USER_ALL) {
18967            users = sUserManager.getUserIds();
18968        } else {
18969            users = new int[] { userId };
18970        }
18971        final ClearStorageConnection conn = new ClearStorageConnection();
18972        if (mContext.bindServiceAsUser(
18973                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18974            try {
18975                for (int curUser : users) {
18976                    long timeout = SystemClock.uptimeMillis() + 5000;
18977                    synchronized (conn) {
18978                        long now;
18979                        while (conn.mContainerService == null &&
18980                                (now = SystemClock.uptimeMillis()) < timeout) {
18981                            try {
18982                                conn.wait(timeout - now);
18983                            } catch (InterruptedException e) {
18984                            }
18985                        }
18986                    }
18987                    if (conn.mContainerService == null) {
18988                        return;
18989                    }
18990
18991                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18992                    clearDirectory(conn.mContainerService,
18993                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18994                    if (allData) {
18995                        clearDirectory(conn.mContainerService,
18996                                userEnv.buildExternalStorageAppDataDirs(packageName));
18997                        clearDirectory(conn.mContainerService,
18998                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18999                    }
19000                }
19001            } finally {
19002                mContext.unbindService(conn);
19003            }
19004        }
19005    }
19006
19007    @Override
19008    public void clearApplicationProfileData(String packageName) {
19009        enforceSystemOrRoot("Only the system can clear all profile data");
19010
19011        final PackageParser.Package pkg;
19012        synchronized (mPackages) {
19013            pkg = mPackages.get(packageName);
19014        }
19015
19016        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19017            synchronized (mInstallLock) {
19018                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19019            }
19020        }
19021    }
19022
19023    @Override
19024    public void clearApplicationUserData(final String packageName,
19025            final IPackageDataObserver observer, final int userId) {
19026        mContext.enforceCallingOrSelfPermission(
19027                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19028
19029        final int callingUid = Binder.getCallingUid();
19030        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19031                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19032
19033        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19034        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
19035        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19036            throw new SecurityException("Cannot clear data for a protected package: "
19037                    + packageName);
19038        }
19039        // Queue up an async operation since the package deletion may take a little while.
19040        mHandler.post(new Runnable() {
19041            public void run() {
19042                mHandler.removeCallbacks(this);
19043                final boolean succeeded;
19044                if (!filterApp) {
19045                    try (PackageFreezer freezer = freezePackage(packageName,
19046                            "clearApplicationUserData")) {
19047                        synchronized (mInstallLock) {
19048                            succeeded = clearApplicationUserDataLIF(packageName, userId);
19049                        }
19050                        clearExternalStorageDataSync(packageName, userId, true);
19051                        synchronized (mPackages) {
19052                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19053                                    packageName, userId);
19054                        }
19055                    }
19056                    if (succeeded) {
19057                        // invoke DeviceStorageMonitor's update method to clear any notifications
19058                        DeviceStorageMonitorInternal dsm = LocalServices
19059                                .getService(DeviceStorageMonitorInternal.class);
19060                        if (dsm != null) {
19061                            dsm.checkMemory();
19062                        }
19063                    }
19064                } else {
19065                    succeeded = false;
19066                }
19067                if (observer != null) {
19068                    try {
19069                        observer.onRemoveCompleted(packageName, succeeded);
19070                    } catch (RemoteException e) {
19071                        Log.i(TAG, "Observer no longer exists.");
19072                    }
19073                } //end if observer
19074            } //end run
19075        });
19076    }
19077
19078    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19079        if (packageName == null) {
19080            Slog.w(TAG, "Attempt to delete null packageName.");
19081            return false;
19082        }
19083
19084        // Try finding details about the requested package
19085        PackageParser.Package pkg;
19086        synchronized (mPackages) {
19087            pkg = mPackages.get(packageName);
19088            if (pkg == null) {
19089                final PackageSetting ps = mSettings.mPackages.get(packageName);
19090                if (ps != null) {
19091                    pkg = ps.pkg;
19092                }
19093            }
19094
19095            if (pkg == null) {
19096                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19097                return false;
19098            }
19099
19100            PackageSetting ps = (PackageSetting) pkg.mExtras;
19101            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19102        }
19103
19104        clearAppDataLIF(pkg, userId,
19105                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19106
19107        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19108        removeKeystoreDataIfNeeded(userId, appId);
19109
19110        UserManagerInternal umInternal = getUserManagerInternal();
19111        final int flags;
19112        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19113            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19114        } else if (umInternal.isUserRunning(userId)) {
19115            flags = StorageManager.FLAG_STORAGE_DE;
19116        } else {
19117            flags = 0;
19118        }
19119        prepareAppDataContentsLIF(pkg, userId, flags);
19120
19121        return true;
19122    }
19123
19124    /**
19125     * Reverts user permission state changes (permissions and flags) in
19126     * all packages for a given user.
19127     *
19128     * @param userId The device user for which to do a reset.
19129     */
19130    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19131        final int packageCount = mPackages.size();
19132        for (int i = 0; i < packageCount; i++) {
19133            PackageParser.Package pkg = mPackages.valueAt(i);
19134            PackageSetting ps = (PackageSetting) pkg.mExtras;
19135            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19136        }
19137    }
19138
19139    private void resetNetworkPolicies(int userId) {
19140        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19141    }
19142
19143    /**
19144     * Reverts user permission state changes (permissions and flags).
19145     *
19146     * @param ps The package for which to reset.
19147     * @param userId The device user for which to do a reset.
19148     */
19149    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19150            final PackageSetting ps, final int userId) {
19151        if (ps.pkg == null) {
19152            return;
19153        }
19154
19155        // These are flags that can change base on user actions.
19156        final int userSettableMask = FLAG_PERMISSION_USER_SET
19157                | FLAG_PERMISSION_USER_FIXED
19158                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19159                | FLAG_PERMISSION_REVIEW_REQUIRED;
19160
19161        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19162                | FLAG_PERMISSION_POLICY_FIXED;
19163
19164        boolean writeInstallPermissions = false;
19165        boolean writeRuntimePermissions = false;
19166
19167        final int permissionCount = ps.pkg.requestedPermissions.size();
19168        for (int i = 0; i < permissionCount; i++) {
19169            final String permName = ps.pkg.requestedPermissions.get(i);
19170            final BasePermission bp =
19171                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
19172            if (bp == null) {
19173                continue;
19174            }
19175
19176            // If shared user we just reset the state to which only this app contributed.
19177            if (ps.sharedUser != null) {
19178                boolean used = false;
19179                final int packageCount = ps.sharedUser.packages.size();
19180                for (int j = 0; j < packageCount; j++) {
19181                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19182                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19183                            && pkg.pkg.requestedPermissions.contains(permName)) {
19184                        used = true;
19185                        break;
19186                    }
19187                }
19188                if (used) {
19189                    continue;
19190                }
19191            }
19192
19193            final PermissionsState permissionsState = ps.getPermissionsState();
19194
19195            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
19196
19197            // Always clear the user settable flags.
19198            final boolean hasInstallState =
19199                    permissionsState.getInstallPermissionState(permName) != null;
19200            // If permission review is enabled and this is a legacy app, mark the
19201            // permission as requiring a review as this is the initial state.
19202            int flags = 0;
19203            if (mSettings.mPermissions.mPermissionReviewRequired
19204                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19205                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19206            }
19207            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19208                if (hasInstallState) {
19209                    writeInstallPermissions = true;
19210                } else {
19211                    writeRuntimePermissions = true;
19212                }
19213            }
19214
19215            // Below is only runtime permission handling.
19216            if (!bp.isRuntime()) {
19217                continue;
19218            }
19219
19220            // Never clobber system or policy.
19221            if ((oldFlags & policyOrSystemFlags) != 0) {
19222                continue;
19223            }
19224
19225            // If this permission was granted by default, make sure it is.
19226            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19227                if (permissionsState.grantRuntimePermission(bp, userId)
19228                        != PERMISSION_OPERATION_FAILURE) {
19229                    writeRuntimePermissions = true;
19230                }
19231            // If permission review is enabled the permissions for a legacy apps
19232            // are represented as constantly granted runtime ones, so don't revoke.
19233            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19234                // Otherwise, reset the permission.
19235                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19236                switch (revokeResult) {
19237                    case PERMISSION_OPERATION_SUCCESS:
19238                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19239                        writeRuntimePermissions = true;
19240                        final int appId = ps.appId;
19241                        mHandler.post(new Runnable() {
19242                            @Override
19243                            public void run() {
19244                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19245                            }
19246                        });
19247                    } break;
19248                }
19249            }
19250        }
19251
19252        // Synchronously write as we are taking permissions away.
19253        if (writeRuntimePermissions) {
19254            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19255        }
19256
19257        // Synchronously write as we are taking permissions away.
19258        if (writeInstallPermissions) {
19259            mSettings.writeLPr();
19260        }
19261    }
19262
19263    /**
19264     * Remove entries from the keystore daemon. Will only remove it if the
19265     * {@code appId} is valid.
19266     */
19267    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19268        if (appId < 0) {
19269            return;
19270        }
19271
19272        final KeyStore keyStore = KeyStore.getInstance();
19273        if (keyStore != null) {
19274            if (userId == UserHandle.USER_ALL) {
19275                for (final int individual : sUserManager.getUserIds()) {
19276                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19277                }
19278            } else {
19279                keyStore.clearUid(UserHandle.getUid(userId, appId));
19280            }
19281        } else {
19282            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19283        }
19284    }
19285
19286    @Override
19287    public void deleteApplicationCacheFiles(final String packageName,
19288            final IPackageDataObserver observer) {
19289        final int userId = UserHandle.getCallingUserId();
19290        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19291    }
19292
19293    @Override
19294    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19295            final IPackageDataObserver observer) {
19296        final int callingUid = Binder.getCallingUid();
19297        if (mContext.checkCallingOrSelfPermission(
19298                android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES)
19299                != PackageManager.PERMISSION_GRANTED) {
19300            // If the caller has the old delete cache permission, silently ignore.  Else throw.
19301            if (mContext.checkCallingOrSelfPermission(
19302                    android.Manifest.permission.DELETE_CACHE_FILES)
19303                    == PackageManager.PERMISSION_GRANTED) {
19304                Slog.w(TAG, "Calling uid " + callingUid + " does not have " +
19305                        android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES +
19306                        ", silently ignoring");
19307                return;
19308            }
19309            mContext.enforceCallingOrSelfPermission(
19310                    android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES, null);
19311        }
19312        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19313                /* requireFullPermission= */ true, /* checkShell= */ false,
19314                "delete application cache files");
19315        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
19316                android.Manifest.permission.ACCESS_INSTANT_APPS);
19317
19318        final PackageParser.Package pkg;
19319        synchronized (mPackages) {
19320            pkg = mPackages.get(packageName);
19321        }
19322
19323        // Queue up an async operation since the package deletion may take a little while.
19324        mHandler.post(new Runnable() {
19325            public void run() {
19326                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
19327                boolean doClearData = true;
19328                if (ps != null) {
19329                    final boolean targetIsInstantApp =
19330                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19331                    doClearData = !targetIsInstantApp
19332                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
19333                }
19334                if (doClearData) {
19335                    synchronized (mInstallLock) {
19336                        final int flags = StorageManager.FLAG_STORAGE_DE
19337                                | StorageManager.FLAG_STORAGE_CE;
19338                        // We're only clearing cache files, so we don't care if the
19339                        // app is unfrozen and still able to run
19340                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19341                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19342                    }
19343                    clearExternalStorageDataSync(packageName, userId, false);
19344                }
19345                if (observer != null) {
19346                    try {
19347                        observer.onRemoveCompleted(packageName, true);
19348                    } catch (RemoteException e) {
19349                        Log.i(TAG, "Observer no longer exists.");
19350                    }
19351                }
19352            }
19353        });
19354    }
19355
19356    @Override
19357    public void getPackageSizeInfo(final String packageName, int userHandle,
19358            final IPackageStatsObserver observer) {
19359        throw new UnsupportedOperationException(
19360                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19361    }
19362
19363    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19364        final PackageSetting ps;
19365        synchronized (mPackages) {
19366            ps = mSettings.mPackages.get(packageName);
19367            if (ps == null) {
19368                Slog.w(TAG, "Failed to find settings for " + packageName);
19369                return false;
19370            }
19371        }
19372
19373        final String[] packageNames = { packageName };
19374        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19375        final String[] codePaths = { ps.codePathString };
19376
19377        try {
19378            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19379                    ps.appId, ceDataInodes, codePaths, stats);
19380
19381            // For now, ignore code size of packages on system partition
19382            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19383                stats.codeSize = 0;
19384            }
19385
19386            // External clients expect these to be tracked separately
19387            stats.dataSize -= stats.cacheSize;
19388
19389        } catch (InstallerException e) {
19390            Slog.w(TAG, String.valueOf(e));
19391            return false;
19392        }
19393
19394        return true;
19395    }
19396
19397    private int getUidTargetSdkVersionLockedLPr(int uid) {
19398        Object obj = mSettings.getUserIdLPr(uid);
19399        if (obj instanceof SharedUserSetting) {
19400            final SharedUserSetting sus = (SharedUserSetting) obj;
19401            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19402            final Iterator<PackageSetting> it = sus.packages.iterator();
19403            while (it.hasNext()) {
19404                final PackageSetting ps = it.next();
19405                if (ps.pkg != null) {
19406                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19407                    if (v < vers) vers = v;
19408                }
19409            }
19410            return vers;
19411        } else if (obj instanceof PackageSetting) {
19412            final PackageSetting ps = (PackageSetting) obj;
19413            if (ps.pkg != null) {
19414                return ps.pkg.applicationInfo.targetSdkVersion;
19415            }
19416        }
19417        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19418    }
19419
19420    private int getPackageTargetSdkVersionLockedLPr(String packageName) {
19421        final PackageParser.Package p = mPackages.get(packageName);
19422        if (p != null) {
19423            return p.applicationInfo.targetSdkVersion;
19424        }
19425        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19426    }
19427
19428    @Override
19429    public void addPreferredActivity(IntentFilter filter, int match,
19430            ComponentName[] set, ComponentName activity, int userId) {
19431        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19432                "Adding preferred");
19433    }
19434
19435    private void addPreferredActivityInternal(IntentFilter filter, int match,
19436            ComponentName[] set, ComponentName activity, boolean always, int userId,
19437            String opname) {
19438        // writer
19439        int callingUid = Binder.getCallingUid();
19440        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19441                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19442        if (filter.countActions() == 0) {
19443            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19444            return;
19445        }
19446        synchronized (mPackages) {
19447            if (mContext.checkCallingOrSelfPermission(
19448                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19449                    != PackageManager.PERMISSION_GRANTED) {
19450                if (getUidTargetSdkVersionLockedLPr(callingUid)
19451                        < Build.VERSION_CODES.FROYO) {
19452                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19453                            + callingUid);
19454                    return;
19455                }
19456                mContext.enforceCallingOrSelfPermission(
19457                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19458            }
19459
19460            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19461            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19462                    + userId + ":");
19463            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19464            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19465            scheduleWritePackageRestrictionsLocked(userId);
19466            postPreferredActivityChangedBroadcast(userId);
19467        }
19468    }
19469
19470    private void postPreferredActivityChangedBroadcast(int userId) {
19471        mHandler.post(() -> {
19472            final IActivityManager am = ActivityManager.getService();
19473            if (am == null) {
19474                return;
19475            }
19476
19477            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19478            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19479            try {
19480                am.broadcastIntent(null, intent, null, null,
19481                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19482                        null, false, false, userId);
19483            } catch (RemoteException e) {
19484            }
19485        });
19486    }
19487
19488    @Override
19489    public void replacePreferredActivity(IntentFilter filter, int match,
19490            ComponentName[] set, ComponentName activity, int userId) {
19491        if (filter.countActions() != 1) {
19492            throw new IllegalArgumentException(
19493                    "replacePreferredActivity expects filter to have only 1 action.");
19494        }
19495        if (filter.countDataAuthorities() != 0
19496                || filter.countDataPaths() != 0
19497                || filter.countDataSchemes() > 1
19498                || filter.countDataTypes() != 0) {
19499            throw new IllegalArgumentException(
19500                    "replacePreferredActivity expects filter to have no data authorities, " +
19501                    "paths, or types; and at most one scheme.");
19502        }
19503
19504        final int callingUid = Binder.getCallingUid();
19505        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19506                true /* requireFullPermission */, false /* checkShell */,
19507                "replace preferred activity");
19508        synchronized (mPackages) {
19509            if (mContext.checkCallingOrSelfPermission(
19510                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19511                    != PackageManager.PERMISSION_GRANTED) {
19512                if (getUidTargetSdkVersionLockedLPr(callingUid)
19513                        < Build.VERSION_CODES.FROYO) {
19514                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19515                            + Binder.getCallingUid());
19516                    return;
19517                }
19518                mContext.enforceCallingOrSelfPermission(
19519                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19520            }
19521
19522            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19523            if (pir != null) {
19524                // Get all of the existing entries that exactly match this filter.
19525                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19526                if (existing != null && existing.size() == 1) {
19527                    PreferredActivity cur = existing.get(0);
19528                    if (DEBUG_PREFERRED) {
19529                        Slog.i(TAG, "Checking replace of preferred:");
19530                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19531                        if (!cur.mPref.mAlways) {
19532                            Slog.i(TAG, "  -- CUR; not mAlways!");
19533                        } else {
19534                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19535                            Slog.i(TAG, "  -- CUR: mSet="
19536                                    + Arrays.toString(cur.mPref.mSetComponents));
19537                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19538                            Slog.i(TAG, "  -- NEW: mMatch="
19539                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19540                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19541                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19542                        }
19543                    }
19544                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19545                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19546                            && cur.mPref.sameSet(set)) {
19547                        // Setting the preferred activity to what it happens to be already
19548                        if (DEBUG_PREFERRED) {
19549                            Slog.i(TAG, "Replacing with same preferred activity "
19550                                    + cur.mPref.mShortComponent + " for user "
19551                                    + userId + ":");
19552                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19553                        }
19554                        return;
19555                    }
19556                }
19557
19558                if (existing != null) {
19559                    if (DEBUG_PREFERRED) {
19560                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19561                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19562                    }
19563                    for (int i = 0; i < existing.size(); i++) {
19564                        PreferredActivity pa = existing.get(i);
19565                        if (DEBUG_PREFERRED) {
19566                            Slog.i(TAG, "Removing existing preferred activity "
19567                                    + pa.mPref.mComponent + ":");
19568                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19569                        }
19570                        pir.removeFilter(pa);
19571                    }
19572                }
19573            }
19574            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19575                    "Replacing preferred");
19576        }
19577    }
19578
19579    @Override
19580    public void clearPackagePreferredActivities(String packageName) {
19581        final int callingUid = Binder.getCallingUid();
19582        if (getInstantAppPackageName(callingUid) != null) {
19583            return;
19584        }
19585        // writer
19586        synchronized (mPackages) {
19587            PackageParser.Package pkg = mPackages.get(packageName);
19588            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
19589                if (mContext.checkCallingOrSelfPermission(
19590                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19591                        != PackageManager.PERMISSION_GRANTED) {
19592                    if (getUidTargetSdkVersionLockedLPr(callingUid)
19593                            < Build.VERSION_CODES.FROYO) {
19594                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19595                                + callingUid);
19596                        return;
19597                    }
19598                    mContext.enforceCallingOrSelfPermission(
19599                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19600                }
19601            }
19602            final PackageSetting ps = mSettings.getPackageLPr(packageName);
19603            if (ps != null
19604                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
19605                return;
19606            }
19607            int user = UserHandle.getCallingUserId();
19608            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19609                scheduleWritePackageRestrictionsLocked(user);
19610            }
19611        }
19612    }
19613
19614    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19615    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19616        ArrayList<PreferredActivity> removed = null;
19617        boolean changed = false;
19618        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19619            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19620            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19621            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19622                continue;
19623            }
19624            Iterator<PreferredActivity> it = pir.filterIterator();
19625            while (it.hasNext()) {
19626                PreferredActivity pa = it.next();
19627                // Mark entry for removal only if it matches the package name
19628                // and the entry is of type "always".
19629                if (packageName == null ||
19630                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19631                                && pa.mPref.mAlways)) {
19632                    if (removed == null) {
19633                        removed = new ArrayList<PreferredActivity>();
19634                    }
19635                    removed.add(pa);
19636                }
19637            }
19638            if (removed != null) {
19639                for (int j=0; j<removed.size(); j++) {
19640                    PreferredActivity pa = removed.get(j);
19641                    pir.removeFilter(pa);
19642                }
19643                changed = true;
19644            }
19645        }
19646        if (changed) {
19647            postPreferredActivityChangedBroadcast(userId);
19648        }
19649        return changed;
19650    }
19651
19652    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19653    private void clearIntentFilterVerificationsLPw(int userId) {
19654        final int packageCount = mPackages.size();
19655        for (int i = 0; i < packageCount; i++) {
19656            PackageParser.Package pkg = mPackages.valueAt(i);
19657            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19658        }
19659    }
19660
19661    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19662    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19663        if (userId == UserHandle.USER_ALL) {
19664            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19665                    sUserManager.getUserIds())) {
19666                for (int oneUserId : sUserManager.getUserIds()) {
19667                    scheduleWritePackageRestrictionsLocked(oneUserId);
19668                }
19669            }
19670        } else {
19671            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19672                scheduleWritePackageRestrictionsLocked(userId);
19673            }
19674        }
19675    }
19676
19677    /** Clears state for all users, and touches intent filter verification policy */
19678    void clearDefaultBrowserIfNeeded(String packageName) {
19679        for (int oneUserId : sUserManager.getUserIds()) {
19680            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19681        }
19682    }
19683
19684    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19685        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19686        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19687            if (packageName.equals(defaultBrowserPackageName)) {
19688                setDefaultBrowserPackageName(null, userId);
19689            }
19690        }
19691    }
19692
19693    @Override
19694    public void resetApplicationPreferences(int userId) {
19695        mContext.enforceCallingOrSelfPermission(
19696                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19697        final long identity = Binder.clearCallingIdentity();
19698        // writer
19699        try {
19700            synchronized (mPackages) {
19701                clearPackagePreferredActivitiesLPw(null, userId);
19702                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19703                // TODO: We have to reset the default SMS and Phone. This requires
19704                // significant refactoring to keep all default apps in the package
19705                // manager (cleaner but more work) or have the services provide
19706                // callbacks to the package manager to request a default app reset.
19707                applyFactoryDefaultBrowserLPw(userId);
19708                clearIntentFilterVerificationsLPw(userId);
19709                primeDomainVerificationsLPw(userId);
19710                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19711                scheduleWritePackageRestrictionsLocked(userId);
19712            }
19713            resetNetworkPolicies(userId);
19714        } finally {
19715            Binder.restoreCallingIdentity(identity);
19716        }
19717    }
19718
19719    @Override
19720    public int getPreferredActivities(List<IntentFilter> outFilters,
19721            List<ComponentName> outActivities, String packageName) {
19722        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19723            return 0;
19724        }
19725        int num = 0;
19726        final int userId = UserHandle.getCallingUserId();
19727        // reader
19728        synchronized (mPackages) {
19729            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19730            if (pir != null) {
19731                final Iterator<PreferredActivity> it = pir.filterIterator();
19732                while (it.hasNext()) {
19733                    final PreferredActivity pa = it.next();
19734                    if (packageName == null
19735                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19736                                    && pa.mPref.mAlways)) {
19737                        if (outFilters != null) {
19738                            outFilters.add(new IntentFilter(pa));
19739                        }
19740                        if (outActivities != null) {
19741                            outActivities.add(pa.mPref.mComponent);
19742                        }
19743                    }
19744                }
19745            }
19746        }
19747
19748        return num;
19749    }
19750
19751    @Override
19752    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19753            int userId) {
19754        int callingUid = Binder.getCallingUid();
19755        if (callingUid != Process.SYSTEM_UID) {
19756            throw new SecurityException(
19757                    "addPersistentPreferredActivity can only be run by the system");
19758        }
19759        if (filter.countActions() == 0) {
19760            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19761            return;
19762        }
19763        synchronized (mPackages) {
19764            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19765                    ":");
19766            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19767            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19768                    new PersistentPreferredActivity(filter, activity));
19769            scheduleWritePackageRestrictionsLocked(userId);
19770            postPreferredActivityChangedBroadcast(userId);
19771        }
19772    }
19773
19774    @Override
19775    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19776        int callingUid = Binder.getCallingUid();
19777        if (callingUid != Process.SYSTEM_UID) {
19778            throw new SecurityException(
19779                    "clearPackagePersistentPreferredActivities can only be run by the system");
19780        }
19781        ArrayList<PersistentPreferredActivity> removed = null;
19782        boolean changed = false;
19783        synchronized (mPackages) {
19784            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19785                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19786                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19787                        .valueAt(i);
19788                if (userId != thisUserId) {
19789                    continue;
19790                }
19791                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19792                while (it.hasNext()) {
19793                    PersistentPreferredActivity ppa = it.next();
19794                    // Mark entry for removal only if it matches the package name.
19795                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19796                        if (removed == null) {
19797                            removed = new ArrayList<PersistentPreferredActivity>();
19798                        }
19799                        removed.add(ppa);
19800                    }
19801                }
19802                if (removed != null) {
19803                    for (int j=0; j<removed.size(); j++) {
19804                        PersistentPreferredActivity ppa = removed.get(j);
19805                        ppir.removeFilter(ppa);
19806                    }
19807                    changed = true;
19808                }
19809            }
19810
19811            if (changed) {
19812                scheduleWritePackageRestrictionsLocked(userId);
19813                postPreferredActivityChangedBroadcast(userId);
19814            }
19815        }
19816    }
19817
19818    /**
19819     * Common machinery for picking apart a restored XML blob and passing
19820     * it to a caller-supplied functor to be applied to the running system.
19821     */
19822    private void restoreFromXml(XmlPullParser parser, int userId,
19823            String expectedStartTag, BlobXmlRestorer functor)
19824            throws IOException, XmlPullParserException {
19825        int type;
19826        while ((type = parser.next()) != XmlPullParser.START_TAG
19827                && type != XmlPullParser.END_DOCUMENT) {
19828        }
19829        if (type != XmlPullParser.START_TAG) {
19830            // oops didn't find a start tag?!
19831            if (DEBUG_BACKUP) {
19832                Slog.e(TAG, "Didn't find start tag during restore");
19833            }
19834            return;
19835        }
19836Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19837        // this is supposed to be TAG_PREFERRED_BACKUP
19838        if (!expectedStartTag.equals(parser.getName())) {
19839            if (DEBUG_BACKUP) {
19840                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19841            }
19842            return;
19843        }
19844
19845        // skip interfering stuff, then we're aligned with the backing implementation
19846        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19847Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19848        functor.apply(parser, userId);
19849    }
19850
19851    private interface BlobXmlRestorer {
19852        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19853    }
19854
19855    /**
19856     * Non-Binder method, support for the backup/restore mechanism: write the
19857     * full set of preferred activities in its canonical XML format.  Returns the
19858     * XML output as a byte array, or null if there is none.
19859     */
19860    @Override
19861    public byte[] getPreferredActivityBackup(int userId) {
19862        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19863            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19864        }
19865
19866        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19867        try {
19868            final XmlSerializer serializer = new FastXmlSerializer();
19869            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19870            serializer.startDocument(null, true);
19871            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19872
19873            synchronized (mPackages) {
19874                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19875            }
19876
19877            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19878            serializer.endDocument();
19879            serializer.flush();
19880        } catch (Exception e) {
19881            if (DEBUG_BACKUP) {
19882                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19883            }
19884            return null;
19885        }
19886
19887        return dataStream.toByteArray();
19888    }
19889
19890    @Override
19891    public void restorePreferredActivities(byte[] backup, int userId) {
19892        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19893            throw new SecurityException("Only the system may call restorePreferredActivities()");
19894        }
19895
19896        try {
19897            final XmlPullParser parser = Xml.newPullParser();
19898            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19899            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19900                    new BlobXmlRestorer() {
19901                        @Override
19902                        public void apply(XmlPullParser parser, int userId)
19903                                throws XmlPullParserException, IOException {
19904                            synchronized (mPackages) {
19905                                mSettings.readPreferredActivitiesLPw(parser, userId);
19906                            }
19907                        }
19908                    } );
19909        } catch (Exception e) {
19910            if (DEBUG_BACKUP) {
19911                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19912            }
19913        }
19914    }
19915
19916    /**
19917     * Non-Binder method, support for the backup/restore mechanism: write the
19918     * default browser (etc) settings in its canonical XML format.  Returns the default
19919     * browser XML representation as a byte array, or null if there is none.
19920     */
19921    @Override
19922    public byte[] getDefaultAppsBackup(int userId) {
19923        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19924            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19925        }
19926
19927        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19928        try {
19929            final XmlSerializer serializer = new FastXmlSerializer();
19930            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19931            serializer.startDocument(null, true);
19932            serializer.startTag(null, TAG_DEFAULT_APPS);
19933
19934            synchronized (mPackages) {
19935                mSettings.writeDefaultAppsLPr(serializer, userId);
19936            }
19937
19938            serializer.endTag(null, TAG_DEFAULT_APPS);
19939            serializer.endDocument();
19940            serializer.flush();
19941        } catch (Exception e) {
19942            if (DEBUG_BACKUP) {
19943                Slog.e(TAG, "Unable to write default apps for backup", e);
19944            }
19945            return null;
19946        }
19947
19948        return dataStream.toByteArray();
19949    }
19950
19951    @Override
19952    public void restoreDefaultApps(byte[] backup, int userId) {
19953        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19954            throw new SecurityException("Only the system may call restoreDefaultApps()");
19955        }
19956
19957        try {
19958            final XmlPullParser parser = Xml.newPullParser();
19959            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19960            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19961                    new BlobXmlRestorer() {
19962                        @Override
19963                        public void apply(XmlPullParser parser, int userId)
19964                                throws XmlPullParserException, IOException {
19965                            synchronized (mPackages) {
19966                                mSettings.readDefaultAppsLPw(parser, userId);
19967                            }
19968                        }
19969                    } );
19970        } catch (Exception e) {
19971            if (DEBUG_BACKUP) {
19972                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19973            }
19974        }
19975    }
19976
19977    @Override
19978    public byte[] getIntentFilterVerificationBackup(int userId) {
19979        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19980            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19981        }
19982
19983        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19984        try {
19985            final XmlSerializer serializer = new FastXmlSerializer();
19986            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19987            serializer.startDocument(null, true);
19988            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19989
19990            synchronized (mPackages) {
19991                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19992            }
19993
19994            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19995            serializer.endDocument();
19996            serializer.flush();
19997        } catch (Exception e) {
19998            if (DEBUG_BACKUP) {
19999                Slog.e(TAG, "Unable to write default apps for backup", e);
20000            }
20001            return null;
20002        }
20003
20004        return dataStream.toByteArray();
20005    }
20006
20007    @Override
20008    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20009        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20010            throw new SecurityException("Only the system may call restorePreferredActivities()");
20011        }
20012
20013        try {
20014            final XmlPullParser parser = Xml.newPullParser();
20015            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20016            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20017                    new BlobXmlRestorer() {
20018                        @Override
20019                        public void apply(XmlPullParser parser, int userId)
20020                                throws XmlPullParserException, IOException {
20021                            synchronized (mPackages) {
20022                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20023                                mSettings.writeLPr();
20024                            }
20025                        }
20026                    } );
20027        } catch (Exception e) {
20028            if (DEBUG_BACKUP) {
20029                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20030            }
20031        }
20032    }
20033
20034    @Override
20035    public byte[] getPermissionGrantBackup(int userId) {
20036        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20037            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20038        }
20039
20040        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20041        try {
20042            final XmlSerializer serializer = new FastXmlSerializer();
20043            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20044            serializer.startDocument(null, true);
20045            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20046
20047            synchronized (mPackages) {
20048                serializeRuntimePermissionGrantsLPr(serializer, userId);
20049            }
20050
20051            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20052            serializer.endDocument();
20053            serializer.flush();
20054        } catch (Exception e) {
20055            if (DEBUG_BACKUP) {
20056                Slog.e(TAG, "Unable to write default apps for backup", e);
20057            }
20058            return null;
20059        }
20060
20061        return dataStream.toByteArray();
20062    }
20063
20064    @Override
20065    public void restorePermissionGrants(byte[] backup, int userId) {
20066        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20067            throw new SecurityException("Only the system may call restorePermissionGrants()");
20068        }
20069
20070        try {
20071            final XmlPullParser parser = Xml.newPullParser();
20072            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20073            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20074                    new BlobXmlRestorer() {
20075                        @Override
20076                        public void apply(XmlPullParser parser, int userId)
20077                                throws XmlPullParserException, IOException {
20078                            synchronized (mPackages) {
20079                                processRestoredPermissionGrantsLPr(parser, userId);
20080                            }
20081                        }
20082                    } );
20083        } catch (Exception e) {
20084            if (DEBUG_BACKUP) {
20085                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20086            }
20087        }
20088    }
20089
20090    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20091            throws IOException {
20092        serializer.startTag(null, TAG_ALL_GRANTS);
20093
20094        final int N = mSettings.mPackages.size();
20095        for (int i = 0; i < N; i++) {
20096            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20097            boolean pkgGrantsKnown = false;
20098
20099            PermissionsState packagePerms = ps.getPermissionsState();
20100
20101            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20102                final int grantFlags = state.getFlags();
20103                // only look at grants that are not system/policy fixed
20104                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20105                    final boolean isGranted = state.isGranted();
20106                    // And only back up the user-twiddled state bits
20107                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20108                        final String packageName = mSettings.mPackages.keyAt(i);
20109                        if (!pkgGrantsKnown) {
20110                            serializer.startTag(null, TAG_GRANT);
20111                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20112                            pkgGrantsKnown = true;
20113                        }
20114
20115                        final boolean userSet =
20116                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20117                        final boolean userFixed =
20118                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20119                        final boolean revoke =
20120                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20121
20122                        serializer.startTag(null, TAG_PERMISSION);
20123                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20124                        if (isGranted) {
20125                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20126                        }
20127                        if (userSet) {
20128                            serializer.attribute(null, ATTR_USER_SET, "true");
20129                        }
20130                        if (userFixed) {
20131                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20132                        }
20133                        if (revoke) {
20134                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20135                        }
20136                        serializer.endTag(null, TAG_PERMISSION);
20137                    }
20138                }
20139            }
20140
20141            if (pkgGrantsKnown) {
20142                serializer.endTag(null, TAG_GRANT);
20143            }
20144        }
20145
20146        serializer.endTag(null, TAG_ALL_GRANTS);
20147    }
20148
20149    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20150            throws XmlPullParserException, IOException {
20151        String pkgName = null;
20152        int outerDepth = parser.getDepth();
20153        int type;
20154        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20155                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20156            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20157                continue;
20158            }
20159
20160            final String tagName = parser.getName();
20161            if (tagName.equals(TAG_GRANT)) {
20162                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20163                if (DEBUG_BACKUP) {
20164                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20165                }
20166            } else if (tagName.equals(TAG_PERMISSION)) {
20167
20168                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20169                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20170
20171                int newFlagSet = 0;
20172                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20173                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20174                }
20175                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20176                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20177                }
20178                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20179                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20180                }
20181                if (DEBUG_BACKUP) {
20182                    Slog.v(TAG, "  + Restoring grant:"
20183                            + " pkg=" + pkgName
20184                            + " perm=" + permName
20185                            + " granted=" + isGranted
20186                            + " bits=0x" + Integer.toHexString(newFlagSet));
20187                }
20188                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20189                if (ps != null) {
20190                    // Already installed so we apply the grant immediately
20191                    if (DEBUG_BACKUP) {
20192                        Slog.v(TAG, "        + already installed; applying");
20193                    }
20194                    PermissionsState perms = ps.getPermissionsState();
20195                    BasePermission bp =
20196                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
20197                    if (bp != null) {
20198                        if (isGranted) {
20199                            perms.grantRuntimePermission(bp, userId);
20200                        }
20201                        if (newFlagSet != 0) {
20202                            perms.updatePermissionFlags(
20203                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20204                        }
20205                    }
20206                } else {
20207                    // Need to wait for post-restore install to apply the grant
20208                    if (DEBUG_BACKUP) {
20209                        Slog.v(TAG, "        - not yet installed; saving for later");
20210                    }
20211                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20212                            isGranted, newFlagSet, userId);
20213                }
20214            } else {
20215                PackageManagerService.reportSettingsProblem(Log.WARN,
20216                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20217                XmlUtils.skipCurrentTag(parser);
20218            }
20219        }
20220
20221        scheduleWriteSettingsLocked();
20222        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20223    }
20224
20225    @Override
20226    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20227            int sourceUserId, int targetUserId, int flags) {
20228        mContext.enforceCallingOrSelfPermission(
20229                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20230        int callingUid = Binder.getCallingUid();
20231        enforceOwnerRights(ownerPackage, callingUid);
20232        PackageManagerServiceUtils.enforceShellRestriction(
20233                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20234        if (intentFilter.countActions() == 0) {
20235            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20236            return;
20237        }
20238        synchronized (mPackages) {
20239            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20240                    ownerPackage, targetUserId, flags);
20241            CrossProfileIntentResolver resolver =
20242                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20243            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20244            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20245            if (existing != null) {
20246                int size = existing.size();
20247                for (int i = 0; i < size; i++) {
20248                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20249                        return;
20250                    }
20251                }
20252            }
20253            resolver.addFilter(newFilter);
20254            scheduleWritePackageRestrictionsLocked(sourceUserId);
20255        }
20256    }
20257
20258    @Override
20259    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20260        mContext.enforceCallingOrSelfPermission(
20261                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20262        final int callingUid = Binder.getCallingUid();
20263        enforceOwnerRights(ownerPackage, callingUid);
20264        PackageManagerServiceUtils.enforceShellRestriction(
20265                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20266        synchronized (mPackages) {
20267            CrossProfileIntentResolver resolver =
20268                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20269            ArraySet<CrossProfileIntentFilter> set =
20270                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20271            for (CrossProfileIntentFilter filter : set) {
20272                if (filter.getOwnerPackage().equals(ownerPackage)) {
20273                    resolver.removeFilter(filter);
20274                }
20275            }
20276            scheduleWritePackageRestrictionsLocked(sourceUserId);
20277        }
20278    }
20279
20280    // Enforcing that callingUid is owning pkg on userId
20281    private void enforceOwnerRights(String pkg, int callingUid) {
20282        // The system owns everything.
20283        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20284            return;
20285        }
20286        final int callingUserId = UserHandle.getUserId(callingUid);
20287        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20288        if (pi == null) {
20289            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20290                    + callingUserId);
20291        }
20292        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20293            throw new SecurityException("Calling uid " + callingUid
20294                    + " does not own package " + pkg);
20295        }
20296    }
20297
20298    @Override
20299    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20300        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20301            return null;
20302        }
20303        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20304    }
20305
20306    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20307        UserManagerService ums = UserManagerService.getInstance();
20308        if (ums != null) {
20309            final UserInfo parent = ums.getProfileParent(userId);
20310            final int launcherUid = (parent != null) ? parent.id : userId;
20311            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20312            if (launcherComponent != null) {
20313                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20314                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20315                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20316                        .setPackage(launcherComponent.getPackageName());
20317                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20318            }
20319        }
20320    }
20321
20322    /**
20323     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20324     * then reports the most likely home activity or null if there are more than one.
20325     */
20326    private ComponentName getDefaultHomeActivity(int userId) {
20327        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20328        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20329        if (cn != null) {
20330            return cn;
20331        }
20332
20333        // Find the launcher with the highest priority and return that component if there are no
20334        // other home activity with the same priority.
20335        int lastPriority = Integer.MIN_VALUE;
20336        ComponentName lastComponent = null;
20337        final int size = allHomeCandidates.size();
20338        for (int i = 0; i < size; i++) {
20339            final ResolveInfo ri = allHomeCandidates.get(i);
20340            if (ri.priority > lastPriority) {
20341                lastComponent = ri.activityInfo.getComponentName();
20342                lastPriority = ri.priority;
20343            } else if (ri.priority == lastPriority) {
20344                // Two components found with same priority.
20345                lastComponent = null;
20346            }
20347        }
20348        return lastComponent;
20349    }
20350
20351    private Intent getHomeIntent() {
20352        Intent intent = new Intent(Intent.ACTION_MAIN);
20353        intent.addCategory(Intent.CATEGORY_HOME);
20354        intent.addCategory(Intent.CATEGORY_DEFAULT);
20355        return intent;
20356    }
20357
20358    private IntentFilter getHomeFilter() {
20359        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20360        filter.addCategory(Intent.CATEGORY_HOME);
20361        filter.addCategory(Intent.CATEGORY_DEFAULT);
20362        return filter;
20363    }
20364
20365    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20366            int userId) {
20367        Intent intent  = getHomeIntent();
20368        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20369                PackageManager.GET_META_DATA, userId);
20370        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20371                true, false, false, userId);
20372
20373        allHomeCandidates.clear();
20374        if (list != null) {
20375            for (ResolveInfo ri : list) {
20376                allHomeCandidates.add(ri);
20377            }
20378        }
20379        return (preferred == null || preferred.activityInfo == null)
20380                ? null
20381                : new ComponentName(preferred.activityInfo.packageName,
20382                        preferred.activityInfo.name);
20383    }
20384
20385    @Override
20386    public void setHomeActivity(ComponentName comp, int userId) {
20387        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20388            return;
20389        }
20390        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20391        getHomeActivitiesAsUser(homeActivities, userId);
20392
20393        boolean found = false;
20394
20395        final int size = homeActivities.size();
20396        final ComponentName[] set = new ComponentName[size];
20397        for (int i = 0; i < size; i++) {
20398            final ResolveInfo candidate = homeActivities.get(i);
20399            final ActivityInfo info = candidate.activityInfo;
20400            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20401            set[i] = activityName;
20402            if (!found && activityName.equals(comp)) {
20403                found = true;
20404            }
20405        }
20406        if (!found) {
20407            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20408                    + userId);
20409        }
20410        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20411                set, comp, userId);
20412    }
20413
20414    private @Nullable String getSetupWizardPackageName() {
20415        final Intent intent = new Intent(Intent.ACTION_MAIN);
20416        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20417
20418        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20419                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20420                        | MATCH_DISABLED_COMPONENTS,
20421                UserHandle.myUserId());
20422        if (matches.size() == 1) {
20423            return matches.get(0).getComponentInfo().packageName;
20424        } else {
20425            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20426                    + ": matches=" + matches);
20427            return null;
20428        }
20429    }
20430
20431    private @Nullable String getStorageManagerPackageName() {
20432        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20433
20434        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20435                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20436                        | MATCH_DISABLED_COMPONENTS,
20437                UserHandle.myUserId());
20438        if (matches.size() == 1) {
20439            return matches.get(0).getComponentInfo().packageName;
20440        } else {
20441            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20442                    + matches.size() + ": matches=" + matches);
20443            return null;
20444        }
20445    }
20446
20447    @Override
20448    public String getSystemTextClassifierPackageName() {
20449        return mContext.getString(R.string.config_defaultTextClassifierPackage);
20450    }
20451
20452    @Override
20453    public void setApplicationEnabledSetting(String appPackageName,
20454            int newState, int flags, int userId, String callingPackage) {
20455        if (!sUserManager.exists(userId)) return;
20456        if (callingPackage == null) {
20457            callingPackage = Integer.toString(Binder.getCallingUid());
20458        }
20459        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20460    }
20461
20462    @Override
20463    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20464        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20465        synchronized (mPackages) {
20466            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20467            if (pkgSetting != null) {
20468                pkgSetting.setUpdateAvailable(updateAvailable);
20469            }
20470        }
20471    }
20472
20473    @Override
20474    public void setComponentEnabledSetting(ComponentName componentName,
20475            int newState, int flags, int userId) {
20476        if (!sUserManager.exists(userId)) return;
20477        setEnabledSetting(componentName.getPackageName(),
20478                componentName.getClassName(), newState, flags, userId, null);
20479    }
20480
20481    private void setEnabledSetting(final String packageName, String className, int newState,
20482            final int flags, int userId, String callingPackage) {
20483        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20484              || newState == COMPONENT_ENABLED_STATE_ENABLED
20485              || newState == COMPONENT_ENABLED_STATE_DISABLED
20486              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20487              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20488            throw new IllegalArgumentException("Invalid new component state: "
20489                    + newState);
20490        }
20491        PackageSetting pkgSetting;
20492        final int callingUid = Binder.getCallingUid();
20493        final int permission;
20494        if (callingUid == Process.SYSTEM_UID) {
20495            permission = PackageManager.PERMISSION_GRANTED;
20496        } else {
20497            permission = mContext.checkCallingOrSelfPermission(
20498                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20499        }
20500        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20501                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20502        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20503        boolean sendNow = false;
20504        boolean isApp = (className == null);
20505        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
20506        String componentName = isApp ? packageName : className;
20507        int packageUid = -1;
20508        ArrayList<String> components;
20509
20510        // reader
20511        synchronized (mPackages) {
20512            pkgSetting = mSettings.mPackages.get(packageName);
20513            if (pkgSetting == null) {
20514                if (!isCallerInstantApp) {
20515                    if (className == null) {
20516                        throw new IllegalArgumentException("Unknown package: " + packageName);
20517                    }
20518                    throw new IllegalArgumentException(
20519                            "Unknown component: " + packageName + "/" + className);
20520                } else {
20521                    // throw SecurityException to prevent leaking package information
20522                    throw new SecurityException(
20523                            "Attempt to change component state; "
20524                            + "pid=" + Binder.getCallingPid()
20525                            + ", uid=" + callingUid
20526                            + (className == null
20527                                    ? ", package=" + packageName
20528                                    : ", component=" + packageName + "/" + className));
20529                }
20530            }
20531        }
20532
20533        // Limit who can change which apps
20534        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
20535            // Don't allow apps that don't have permission to modify other apps
20536            if (!allowedByPermission
20537                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
20538                throw new SecurityException(
20539                        "Attempt to change component state; "
20540                        + "pid=" + Binder.getCallingPid()
20541                        + ", uid=" + callingUid
20542                        + (className == null
20543                                ? ", package=" + packageName
20544                                : ", component=" + packageName + "/" + className));
20545            }
20546            // Don't allow changing protected packages.
20547            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20548                throw new SecurityException("Cannot disable a protected package: " + packageName);
20549            }
20550        }
20551
20552        synchronized (mPackages) {
20553            if (callingUid == Process.SHELL_UID
20554                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20555                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20556                // unless it is a test package.
20557                int oldState = pkgSetting.getEnabled(userId);
20558                if (className == null
20559                        &&
20560                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20561                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20562                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20563                        &&
20564                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20565                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
20566                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20567                    // ok
20568                } else {
20569                    throw new SecurityException(
20570                            "Shell cannot change component state for " + packageName + "/"
20571                                    + className + " to " + newState);
20572                }
20573            }
20574        }
20575        if (className == null) {
20576            // We're dealing with an application/package level state change
20577            synchronized (mPackages) {
20578                if (pkgSetting.getEnabled(userId) == newState) {
20579                    // Nothing to do
20580                    return;
20581                }
20582            }
20583            // If we're enabling a system stub, there's a little more work to do.
20584            // Prior to enabling the package, we need to decompress the APK(s) to the
20585            // data partition and then replace the version on the system partition.
20586            final PackageParser.Package deletedPkg = pkgSetting.pkg;
20587            final boolean isSystemStub = deletedPkg.isStub
20588                    && deletedPkg.isSystem();
20589            if (isSystemStub
20590                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20591                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
20592                final File codePath = decompressPackage(deletedPkg);
20593                if (codePath == null) {
20594                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
20595                    return;
20596                }
20597                // TODO remove direct parsing of the package object during internal cleanup
20598                // of scan package
20599                // We need to call parse directly here for no other reason than we need
20600                // the new package in order to disable the old one [we use the information
20601                // for some internal optimization to optionally create a new package setting
20602                // object on replace]. However, we can't get the package from the scan
20603                // because the scan modifies live structures and we need to remove the
20604                // old [system] package from the system before a scan can be attempted.
20605                // Once scan is indempotent we can remove this parse and use the package
20606                // object we scanned, prior to adding it to package settings.
20607                final PackageParser pp = new PackageParser();
20608                pp.setSeparateProcesses(mSeparateProcesses);
20609                pp.setDisplayMetrics(mMetrics);
20610                pp.setCallback(mPackageParserCallback);
20611                final PackageParser.Package tmpPkg;
20612                try {
20613                    final @ParseFlags int parseFlags = mDefParseFlags
20614                            | PackageParser.PARSE_MUST_BE_APK
20615                            | PackageParser.PARSE_IS_SYSTEM_DIR;
20616                    tmpPkg = pp.parsePackage(codePath, parseFlags);
20617                } catch (PackageParserException e) {
20618                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
20619                    return;
20620                }
20621                synchronized (mInstallLock) {
20622                    // Disable the stub and remove any package entries
20623                    removePackageLI(deletedPkg, true);
20624                    synchronized (mPackages) {
20625                        disableSystemPackageLPw(deletedPkg, tmpPkg);
20626                    }
20627                    final PackageParser.Package pkg;
20628                    try (PackageFreezer freezer =
20629                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20630                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
20631                                | PackageParser.PARSE_ENFORCE_CODE;
20632                        pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
20633                                0 /*currentTime*/, null /*user*/);
20634                        prepareAppDataAfterInstallLIF(pkg);
20635                        synchronized (mPackages) {
20636                            try {
20637                                updateSharedLibrariesLPr(pkg, null);
20638                            } catch (PackageManagerException e) {
20639                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
20640                            }
20641                            mPermissionManager.updatePermissions(
20642                                    pkg.packageName, pkg, true, mPackages.values(),
20643                                    mPermissionCallback);
20644                            mSettings.writeLPr();
20645                        }
20646                    } catch (PackageManagerException e) {
20647                        // Whoops! Something went wrong; try to roll back to the stub
20648                        Slog.w(TAG, "Failed to install compressed system package:"
20649                                + pkgSetting.name, e);
20650                        // Remove the failed install
20651                        removeCodePathLI(codePath);
20652
20653                        // Install the system package
20654                        try (PackageFreezer freezer =
20655                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20656                            synchronized (mPackages) {
20657                                // NOTE: The system package always needs to be enabled; even
20658                                // if it's for a compressed stub. If we don't, installing the
20659                                // system package fails during scan [scanning checks the disabled
20660                                // packages]. We will reverse this later, after we've "installed"
20661                                // the stub.
20662                                // This leaves us in a fragile state; the stub should never be
20663                                // enabled, so, cross your fingers and hope nothing goes wrong
20664                                // until we can disable the package later.
20665                                enableSystemPackageLPw(deletedPkg);
20666                            }
20667                            installPackageFromSystemLIF(deletedPkg.codePath,
20668                                    false /*isPrivileged*/, null /*allUserHandles*/,
20669                                    null /*origUserHandles*/, null /*origPermissionsState*/,
20670                                    true /*writeSettings*/);
20671                        } catch (PackageManagerException pme) {
20672                            Slog.w(TAG, "Failed to restore system package:"
20673                                    + deletedPkg.packageName, pme);
20674                        } finally {
20675                            synchronized (mPackages) {
20676                                mSettings.disableSystemPackageLPw(
20677                                        deletedPkg.packageName, true /*replaced*/);
20678                                mSettings.writeLPr();
20679                            }
20680                        }
20681                        return;
20682                    }
20683                    clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
20684                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20685                    mDexManager.notifyPackageUpdated(pkg.packageName,
20686                            pkg.baseCodePath, pkg.splitCodePaths);
20687                }
20688            }
20689            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20690                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20691                // Don't care about who enables an app.
20692                callingPackage = null;
20693            }
20694            synchronized (mPackages) {
20695                pkgSetting.setEnabled(newState, userId, callingPackage);
20696            }
20697        } else {
20698            synchronized (mPackages) {
20699                // We're dealing with a component level state change
20700                // First, verify that this is a valid class name.
20701                PackageParser.Package pkg = pkgSetting.pkg;
20702                if (pkg == null || !pkg.hasComponentClassName(className)) {
20703                    if (pkg != null &&
20704                            pkg.applicationInfo.targetSdkVersion >=
20705                                    Build.VERSION_CODES.JELLY_BEAN) {
20706                        throw new IllegalArgumentException("Component class " + className
20707                                + " does not exist in " + packageName);
20708                    } else {
20709                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20710                                + className + " does not exist in " + packageName);
20711                    }
20712                }
20713                switch (newState) {
20714                    case COMPONENT_ENABLED_STATE_ENABLED:
20715                        if (!pkgSetting.enableComponentLPw(className, userId)) {
20716                            return;
20717                        }
20718                        break;
20719                    case COMPONENT_ENABLED_STATE_DISABLED:
20720                        if (!pkgSetting.disableComponentLPw(className, userId)) {
20721                            return;
20722                        }
20723                        break;
20724                    case COMPONENT_ENABLED_STATE_DEFAULT:
20725                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
20726                            return;
20727                        }
20728                        break;
20729                    default:
20730                        Slog.e(TAG, "Invalid new component state: " + newState);
20731                        return;
20732                }
20733            }
20734        }
20735        synchronized (mPackages) {
20736            scheduleWritePackageRestrictionsLocked(userId);
20737            updateSequenceNumberLP(pkgSetting, new int[] { userId });
20738            final long callingId = Binder.clearCallingIdentity();
20739            try {
20740                updateInstantAppInstallerLocked(packageName);
20741            } finally {
20742                Binder.restoreCallingIdentity(callingId);
20743            }
20744            components = mPendingBroadcasts.get(userId, packageName);
20745            final boolean newPackage = components == null;
20746            if (newPackage) {
20747                components = new ArrayList<String>();
20748            }
20749            if (!components.contains(componentName)) {
20750                components.add(componentName);
20751            }
20752            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20753                sendNow = true;
20754                // Purge entry from pending broadcast list if another one exists already
20755                // since we are sending one right away.
20756                mPendingBroadcasts.remove(userId, packageName);
20757            } else {
20758                if (newPackage) {
20759                    mPendingBroadcasts.put(userId, packageName, components);
20760                }
20761                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20762                    // Schedule a message
20763                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20764                }
20765            }
20766        }
20767
20768        long callingId = Binder.clearCallingIdentity();
20769        try {
20770            if (sendNow) {
20771                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20772                sendPackageChangedBroadcast(packageName,
20773                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20774            }
20775        } finally {
20776            Binder.restoreCallingIdentity(callingId);
20777        }
20778    }
20779
20780    @Override
20781    public void flushPackageRestrictionsAsUser(int userId) {
20782        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20783            return;
20784        }
20785        if (!sUserManager.exists(userId)) {
20786            return;
20787        }
20788        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20789                false /* checkShell */, "flushPackageRestrictions");
20790        synchronized (mPackages) {
20791            mSettings.writePackageRestrictionsLPr(userId);
20792            mDirtyUsers.remove(userId);
20793            if (mDirtyUsers.isEmpty()) {
20794                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20795            }
20796        }
20797    }
20798
20799    private void sendPackageChangedBroadcast(String packageName,
20800            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20801        if (DEBUG_INSTALL)
20802            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20803                    + componentNames);
20804        Bundle extras = new Bundle(4);
20805        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20806        String nameList[] = new String[componentNames.size()];
20807        componentNames.toArray(nameList);
20808        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20809        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20810        extras.putInt(Intent.EXTRA_UID, packageUid);
20811        // If this is not reporting a change of the overall package, then only send it
20812        // to registered receivers.  We don't want to launch a swath of apps for every
20813        // little component state change.
20814        final int flags = !componentNames.contains(packageName)
20815                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20816        final int userId = UserHandle.getUserId(packageUid);
20817        final boolean isInstantApp = isInstantApp(packageName, userId);
20818        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
20819        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
20820        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20821                userIds, instantUserIds);
20822    }
20823
20824    @Override
20825    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20826        if (!sUserManager.exists(userId)) return;
20827        final int callingUid = Binder.getCallingUid();
20828        if (getInstantAppPackageName(callingUid) != null) {
20829            return;
20830        }
20831        final int permission = mContext.checkCallingOrSelfPermission(
20832                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20833        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20834        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20835                true /* requireFullPermission */, true /* checkShell */, "stop package");
20836        // writer
20837        synchronized (mPackages) {
20838            final PackageSetting ps = mSettings.mPackages.get(packageName);
20839            if (!filterAppAccessLPr(ps, callingUid, userId)
20840                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20841                            allowedByPermission, callingUid, userId)) {
20842                scheduleWritePackageRestrictionsLocked(userId);
20843            }
20844        }
20845    }
20846
20847    @Override
20848    public String getInstallerPackageName(String packageName) {
20849        final int callingUid = Binder.getCallingUid();
20850        synchronized (mPackages) {
20851            final PackageSetting ps = mSettings.mPackages.get(packageName);
20852            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20853                return null;
20854            }
20855            return mSettings.getInstallerPackageNameLPr(packageName);
20856        }
20857    }
20858
20859    public boolean isOrphaned(String packageName) {
20860        // reader
20861        synchronized (mPackages) {
20862            return mSettings.isOrphaned(packageName);
20863        }
20864    }
20865
20866    @Override
20867    public int getApplicationEnabledSetting(String packageName, int userId) {
20868        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20869        int callingUid = Binder.getCallingUid();
20870        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20871                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20872        // reader
20873        synchronized (mPackages) {
20874            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
20875                return COMPONENT_ENABLED_STATE_DISABLED;
20876            }
20877            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20878        }
20879    }
20880
20881    @Override
20882    public int getComponentEnabledSetting(ComponentName component, int userId) {
20883        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20884        int callingUid = Binder.getCallingUid();
20885        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20886                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
20887        synchronized (mPackages) {
20888            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
20889                    component, TYPE_UNKNOWN, userId)) {
20890                return COMPONENT_ENABLED_STATE_DISABLED;
20891            }
20892            return mSettings.getComponentEnabledSettingLPr(component, userId);
20893        }
20894    }
20895
20896    @Override
20897    public void enterSafeMode() {
20898        enforceSystemOrRoot("Only the system can request entering safe mode");
20899
20900        if (!mSystemReady) {
20901            mSafeMode = true;
20902        }
20903    }
20904
20905    @Override
20906    public void systemReady() {
20907        enforceSystemOrRoot("Only the system can claim the system is ready");
20908
20909        mSystemReady = true;
20910        final ContentResolver resolver = mContext.getContentResolver();
20911        ContentObserver co = new ContentObserver(mHandler) {
20912            @Override
20913            public void onChange(boolean selfChange) {
20914                mWebInstantAppsDisabled =
20915                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20916                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20917            }
20918        };
20919        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20920                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20921                false, co, UserHandle.USER_SYSTEM);
20922        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Secure
20923                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20924        co.onChange(true);
20925
20926        // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to
20927        // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once
20928        // it is done.
20929        ContentObserver privAppOobObserver = new ContentObserver(mHandler) {
20930            @Override
20931            public void onChange(boolean selfChange) {
20932                int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0);
20933                SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB,
20934                        oobEnabled == 1 ? "true" : "false");
20935            }
20936        };
20937        mContext.getContentResolver().registerContentObserver(
20938                Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver,
20939                UserHandle.USER_SYSTEM);
20940        // At boot, restore the value from the setting, which persists across reboot.
20941        privAppOobObserver.onChange(true);
20942
20943        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20944        // disabled after already being started.
20945        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20946                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20947
20948        // Read the compatibilty setting when the system is ready.
20949        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20950                mContext.getContentResolver(),
20951                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20952        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20953        if (DEBUG_SETTINGS) {
20954            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20955        }
20956
20957        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20958
20959        synchronized (mPackages) {
20960            // Verify that all of the preferred activity components actually
20961            // exist.  It is possible for applications to be updated and at
20962            // that point remove a previously declared activity component that
20963            // had been set as a preferred activity.  We try to clean this up
20964            // the next time we encounter that preferred activity, but it is
20965            // possible for the user flow to never be able to return to that
20966            // situation so here we do a sanity check to make sure we haven't
20967            // left any junk around.
20968            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20969            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20970                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20971                removed.clear();
20972                for (PreferredActivity pa : pir.filterSet()) {
20973                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20974                        removed.add(pa);
20975                    }
20976                }
20977                if (removed.size() > 0) {
20978                    for (int r=0; r<removed.size(); r++) {
20979                        PreferredActivity pa = removed.get(r);
20980                        Slog.w(TAG, "Removing dangling preferred activity: "
20981                                + pa.mPref.mComponent);
20982                        pir.removeFilter(pa);
20983                    }
20984                    mSettings.writePackageRestrictionsLPr(
20985                            mSettings.mPreferredActivities.keyAt(i));
20986                }
20987            }
20988
20989            for (int userId : UserManagerService.getInstance().getUserIds()) {
20990                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20991                    grantPermissionsUserIds = ArrayUtils.appendInt(
20992                            grantPermissionsUserIds, userId);
20993                }
20994            }
20995        }
20996        sUserManager.systemReady();
20997        // If we upgraded grant all default permissions before kicking off.
20998        for (int userId : grantPermissionsUserIds) {
20999            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21000        }
21001
21002        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21003            // If we did not grant default permissions, we preload from this the
21004            // default permission exceptions lazily to ensure we don't hit the
21005            // disk on a new user creation.
21006            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21007        }
21008
21009        // Now that we've scanned all packages, and granted any default
21010        // permissions, ensure permissions are updated. Beware of dragons if you
21011        // try optimizing this.
21012        synchronized (mPackages) {
21013            mPermissionManager.updateAllPermissions(
21014                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
21015                    mPermissionCallback);
21016        }
21017
21018        // Kick off any messages waiting for system ready
21019        if (mPostSystemReadyMessages != null) {
21020            for (Message msg : mPostSystemReadyMessages) {
21021                msg.sendToTarget();
21022            }
21023            mPostSystemReadyMessages = null;
21024        }
21025
21026        // Watch for external volumes that come and go over time
21027        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21028        storage.registerListener(mStorageListener);
21029
21030        mInstallerService.systemReady();
21031        mPackageDexOptimizer.systemReady();
21032
21033        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21034                StorageManagerInternal.class);
21035        StorageManagerInternal.addExternalStoragePolicy(
21036                new StorageManagerInternal.ExternalStorageMountPolicy() {
21037            @Override
21038            public int getMountMode(int uid, String packageName) {
21039                if (Process.isIsolated(uid)) {
21040                    return Zygote.MOUNT_EXTERNAL_NONE;
21041                }
21042                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21043                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21044                }
21045                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21046                    return Zygote.MOUNT_EXTERNAL_READ;
21047                }
21048                return Zygote.MOUNT_EXTERNAL_WRITE;
21049            }
21050
21051            @Override
21052            public boolean hasExternalStorage(int uid, String packageName) {
21053                return true;
21054            }
21055        });
21056
21057        // Now that we're mostly running, clean up stale users and apps
21058        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21059        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21060
21061        mPermissionManager.systemReady();
21062
21063        if (mInstantAppResolverConnection != null) {
21064            mContext.registerReceiver(new BroadcastReceiver() {
21065                @Override
21066                public void onReceive(Context context, Intent intent) {
21067                    mInstantAppResolverConnection.optimisticBind();
21068                    mContext.unregisterReceiver(this);
21069                }
21070            }, new IntentFilter(Intent.ACTION_BOOT_COMPLETED));
21071        }
21072    }
21073
21074    public void waitForAppDataPrepared() {
21075        if (mPrepareAppDataFuture == null) {
21076            return;
21077        }
21078        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21079        mPrepareAppDataFuture = null;
21080    }
21081
21082    @Override
21083    public boolean isSafeMode() {
21084        // allow instant applications
21085        return mSafeMode;
21086    }
21087
21088    @Override
21089    public boolean hasSystemUidErrors() {
21090        // allow instant applications
21091        return mHasSystemUidErrors;
21092    }
21093
21094    static String arrayToString(int[] array) {
21095        StringBuffer buf = new StringBuffer(128);
21096        buf.append('[');
21097        if (array != null) {
21098            for (int i=0; i<array.length; i++) {
21099                if (i > 0) buf.append(", ");
21100                buf.append(array[i]);
21101            }
21102        }
21103        buf.append(']');
21104        return buf.toString();
21105    }
21106
21107    @Override
21108    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21109            FileDescriptor err, String[] args, ShellCallback callback,
21110            ResultReceiver resultReceiver) {
21111        (new PackageManagerShellCommand(this)).exec(
21112                this, in, out, err, args, callback, resultReceiver);
21113    }
21114
21115    @Override
21116    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21117        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21118
21119        DumpState dumpState = new DumpState();
21120        boolean fullPreferred = false;
21121        boolean checkin = false;
21122
21123        String packageName = null;
21124        ArraySet<String> permissionNames = null;
21125
21126        int opti = 0;
21127        while (opti < args.length) {
21128            String opt = args[opti];
21129            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21130                break;
21131            }
21132            opti++;
21133
21134            if ("-a".equals(opt)) {
21135                // Right now we only know how to print all.
21136            } else if ("-h".equals(opt)) {
21137                pw.println("Package manager dump options:");
21138                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21139                pw.println("    --checkin: dump for a checkin");
21140                pw.println("    -f: print details of intent filters");
21141                pw.println("    -h: print this help");
21142                pw.println("  cmd may be one of:");
21143                pw.println("    l[ibraries]: list known shared libraries");
21144                pw.println("    f[eatures]: list device features");
21145                pw.println("    k[eysets]: print known keysets");
21146                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21147                pw.println("    perm[issions]: dump permissions");
21148                pw.println("    permission [name ...]: dump declaration and use of given permission");
21149                pw.println("    pref[erred]: print preferred package settings");
21150                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21151                pw.println("    prov[iders]: dump content providers");
21152                pw.println("    p[ackages]: dump installed packages");
21153                pw.println("    s[hared-users]: dump shared user IDs");
21154                pw.println("    m[essages]: print collected runtime messages");
21155                pw.println("    v[erifiers]: print package verifier info");
21156                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21157                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21158                pw.println("    version: print database version info");
21159                pw.println("    write: write current settings now");
21160                pw.println("    installs: details about install sessions");
21161                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21162                pw.println("    dexopt: dump dexopt state");
21163                pw.println("    compiler-stats: dump compiler statistics");
21164                pw.println("    service-permissions: dump permissions required by services");
21165                pw.println("    <package.name>: info about given package");
21166                return;
21167            } else if ("--checkin".equals(opt)) {
21168                checkin = true;
21169            } else if ("-f".equals(opt)) {
21170                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21171            } else if ("--proto".equals(opt)) {
21172                dumpProto(fd);
21173                return;
21174            } else {
21175                pw.println("Unknown argument: " + opt + "; use -h for help");
21176            }
21177        }
21178
21179        // Is the caller requesting to dump a particular piece of data?
21180        if (opti < args.length) {
21181            String cmd = args[opti];
21182            opti++;
21183            // Is this a package name?
21184            if ("android".equals(cmd) || cmd.contains(".")) {
21185                packageName = cmd;
21186                // When dumping a single package, we always dump all of its
21187                // filter information since the amount of data will be reasonable.
21188                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21189            } else if ("check-permission".equals(cmd)) {
21190                if (opti >= args.length) {
21191                    pw.println("Error: check-permission missing permission argument");
21192                    return;
21193                }
21194                String perm = args[opti];
21195                opti++;
21196                if (opti >= args.length) {
21197                    pw.println("Error: check-permission missing package argument");
21198                    return;
21199                }
21200
21201                String pkg = args[opti];
21202                opti++;
21203                int user = UserHandle.getUserId(Binder.getCallingUid());
21204                if (opti < args.length) {
21205                    try {
21206                        user = Integer.parseInt(args[opti]);
21207                    } catch (NumberFormatException e) {
21208                        pw.println("Error: check-permission user argument is not a number: "
21209                                + args[opti]);
21210                        return;
21211                    }
21212                }
21213
21214                // Normalize package name to handle renamed packages and static libs
21215                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21216
21217                pw.println(checkPermission(perm, pkg, user));
21218                return;
21219            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21220                dumpState.setDump(DumpState.DUMP_LIBS);
21221            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21222                dumpState.setDump(DumpState.DUMP_FEATURES);
21223            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21224                if (opti >= args.length) {
21225                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21226                            | DumpState.DUMP_SERVICE_RESOLVERS
21227                            | DumpState.DUMP_RECEIVER_RESOLVERS
21228                            | DumpState.DUMP_CONTENT_RESOLVERS);
21229                } else {
21230                    while (opti < args.length) {
21231                        String name = args[opti];
21232                        if ("a".equals(name) || "activity".equals(name)) {
21233                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21234                        } else if ("s".equals(name) || "service".equals(name)) {
21235                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21236                        } else if ("r".equals(name) || "receiver".equals(name)) {
21237                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21238                        } else if ("c".equals(name) || "content".equals(name)) {
21239                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21240                        } else {
21241                            pw.println("Error: unknown resolver table type: " + name);
21242                            return;
21243                        }
21244                        opti++;
21245                    }
21246                }
21247            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21248                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21249            } else if ("permission".equals(cmd)) {
21250                if (opti >= args.length) {
21251                    pw.println("Error: permission requires permission name");
21252                    return;
21253                }
21254                permissionNames = new ArraySet<>();
21255                while (opti < args.length) {
21256                    permissionNames.add(args[opti]);
21257                    opti++;
21258                }
21259                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21260                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21261            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21262                dumpState.setDump(DumpState.DUMP_PREFERRED);
21263            } else if ("preferred-xml".equals(cmd)) {
21264                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21265                if (opti < args.length && "--full".equals(args[opti])) {
21266                    fullPreferred = true;
21267                    opti++;
21268                }
21269            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21270                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21271            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21272                dumpState.setDump(DumpState.DUMP_PACKAGES);
21273            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21274                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21275            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21276                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21277            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21278                dumpState.setDump(DumpState.DUMP_MESSAGES);
21279            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21280                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21281            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21282                    || "intent-filter-verifiers".equals(cmd)) {
21283                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21284            } else if ("version".equals(cmd)) {
21285                dumpState.setDump(DumpState.DUMP_VERSION);
21286            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21287                dumpState.setDump(DumpState.DUMP_KEYSETS);
21288            } else if ("installs".equals(cmd)) {
21289                dumpState.setDump(DumpState.DUMP_INSTALLS);
21290            } else if ("frozen".equals(cmd)) {
21291                dumpState.setDump(DumpState.DUMP_FROZEN);
21292            } else if ("volumes".equals(cmd)) {
21293                dumpState.setDump(DumpState.DUMP_VOLUMES);
21294            } else if ("dexopt".equals(cmd)) {
21295                dumpState.setDump(DumpState.DUMP_DEXOPT);
21296            } else if ("compiler-stats".equals(cmd)) {
21297                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21298            } else if ("changes".equals(cmd)) {
21299                dumpState.setDump(DumpState.DUMP_CHANGES);
21300            } else if ("service-permissions".equals(cmd)) {
21301                dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS);
21302            } else if ("write".equals(cmd)) {
21303                synchronized (mPackages) {
21304                    mSettings.writeLPr();
21305                    pw.println("Settings written.");
21306                    return;
21307                }
21308            }
21309        }
21310
21311        if (checkin) {
21312            pw.println("vers,1");
21313        }
21314
21315        // reader
21316        synchronized (mPackages) {
21317            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21318                if (!checkin) {
21319                    if (dumpState.onTitlePrinted())
21320                        pw.println();
21321                    pw.println("Database versions:");
21322                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21323                }
21324            }
21325
21326            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21327                if (!checkin) {
21328                    if (dumpState.onTitlePrinted())
21329                        pw.println();
21330                    pw.println("Verifiers:");
21331                    pw.print("  Required: ");
21332                    pw.print(mRequiredVerifierPackage);
21333                    pw.print(" (uid=");
21334                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21335                            UserHandle.USER_SYSTEM));
21336                    pw.println(")");
21337                } else if (mRequiredVerifierPackage != null) {
21338                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21339                    pw.print(",");
21340                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21341                            UserHandle.USER_SYSTEM));
21342                }
21343            }
21344
21345            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21346                    packageName == null) {
21347                if (mIntentFilterVerifierComponent != null) {
21348                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21349                    if (!checkin) {
21350                        if (dumpState.onTitlePrinted())
21351                            pw.println();
21352                        pw.println("Intent Filter Verifier:");
21353                        pw.print("  Using: ");
21354                        pw.print(verifierPackageName);
21355                        pw.print(" (uid=");
21356                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21357                                UserHandle.USER_SYSTEM));
21358                        pw.println(")");
21359                    } else if (verifierPackageName != null) {
21360                        pw.print("ifv,"); pw.print(verifierPackageName);
21361                        pw.print(",");
21362                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21363                                UserHandle.USER_SYSTEM));
21364                    }
21365                } else {
21366                    pw.println();
21367                    pw.println("No Intent Filter Verifier available!");
21368                }
21369            }
21370
21371            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21372                boolean printedHeader = false;
21373                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21374                while (it.hasNext()) {
21375                    String libName = it.next();
21376                    LongSparseArray<SharedLibraryEntry> versionedLib
21377                            = mSharedLibraries.get(libName);
21378                    if (versionedLib == null) {
21379                        continue;
21380                    }
21381                    final int versionCount = versionedLib.size();
21382                    for (int i = 0; i < versionCount; i++) {
21383                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21384                        if (!checkin) {
21385                            if (!printedHeader) {
21386                                if (dumpState.onTitlePrinted())
21387                                    pw.println();
21388                                pw.println("Libraries:");
21389                                printedHeader = true;
21390                            }
21391                            pw.print("  ");
21392                        } else {
21393                            pw.print("lib,");
21394                        }
21395                        pw.print(libEntry.info.getName());
21396                        if (libEntry.info.isStatic()) {
21397                            pw.print(" version=" + libEntry.info.getLongVersion());
21398                        }
21399                        if (!checkin) {
21400                            pw.print(" -> ");
21401                        }
21402                        if (libEntry.path != null) {
21403                            pw.print(" (jar) ");
21404                            pw.print(libEntry.path);
21405                        } else {
21406                            pw.print(" (apk) ");
21407                            pw.print(libEntry.apk);
21408                        }
21409                        pw.println();
21410                    }
21411                }
21412            }
21413
21414            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21415                if (dumpState.onTitlePrinted())
21416                    pw.println();
21417                if (!checkin) {
21418                    pw.println("Features:");
21419                }
21420
21421                synchronized (mAvailableFeatures) {
21422                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21423                        if (checkin) {
21424                            pw.print("feat,");
21425                            pw.print(feat.name);
21426                            pw.print(",");
21427                            pw.println(feat.version);
21428                        } else {
21429                            pw.print("  ");
21430                            pw.print(feat.name);
21431                            if (feat.version > 0) {
21432                                pw.print(" version=");
21433                                pw.print(feat.version);
21434                            }
21435                            pw.println();
21436                        }
21437                    }
21438                }
21439            }
21440
21441            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21442                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21443                        : "Activity Resolver Table:", "  ", packageName,
21444                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21445                    dumpState.setTitlePrinted(true);
21446                }
21447            }
21448            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21449                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21450                        : "Receiver Resolver Table:", "  ", packageName,
21451                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21452                    dumpState.setTitlePrinted(true);
21453                }
21454            }
21455            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21456                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21457                        : "Service Resolver Table:", "  ", packageName,
21458                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21459                    dumpState.setTitlePrinted(true);
21460                }
21461            }
21462            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21463                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21464                        : "Provider Resolver Table:", "  ", packageName,
21465                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21466                    dumpState.setTitlePrinted(true);
21467                }
21468            }
21469
21470            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21471                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21472                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21473                    int user = mSettings.mPreferredActivities.keyAt(i);
21474                    if (pir.dump(pw,
21475                            dumpState.getTitlePrinted()
21476                                ? "\nPreferred Activities User " + user + ":"
21477                                : "Preferred Activities User " + user + ":", "  ",
21478                            packageName, true, false)) {
21479                        dumpState.setTitlePrinted(true);
21480                    }
21481                }
21482            }
21483
21484            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21485                pw.flush();
21486                FileOutputStream fout = new FileOutputStream(fd);
21487                BufferedOutputStream str = new BufferedOutputStream(fout);
21488                XmlSerializer serializer = new FastXmlSerializer();
21489                try {
21490                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21491                    serializer.startDocument(null, true);
21492                    serializer.setFeature(
21493                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21494                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21495                    serializer.endDocument();
21496                    serializer.flush();
21497                } catch (IllegalArgumentException e) {
21498                    pw.println("Failed writing: " + e);
21499                } catch (IllegalStateException e) {
21500                    pw.println("Failed writing: " + e);
21501                } catch (IOException e) {
21502                    pw.println("Failed writing: " + e);
21503                }
21504            }
21505
21506            if (!checkin
21507                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21508                    && packageName == null) {
21509                pw.println();
21510                int count = mSettings.mPackages.size();
21511                if (count == 0) {
21512                    pw.println("No applications!");
21513                    pw.println();
21514                } else {
21515                    final String prefix = "  ";
21516                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21517                    if (allPackageSettings.size() == 0) {
21518                        pw.println("No domain preferred apps!");
21519                        pw.println();
21520                    } else {
21521                        pw.println("App verification status:");
21522                        pw.println();
21523                        count = 0;
21524                        for (PackageSetting ps : allPackageSettings) {
21525                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21526                            if (ivi == null || ivi.getPackageName() == null) continue;
21527                            pw.println(prefix + "Package: " + ivi.getPackageName());
21528                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21529                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21530                            pw.println();
21531                            count++;
21532                        }
21533                        if (count == 0) {
21534                            pw.println(prefix + "No app verification established.");
21535                            pw.println();
21536                        }
21537                        for (int userId : sUserManager.getUserIds()) {
21538                            pw.println("App linkages for user " + userId + ":");
21539                            pw.println();
21540                            count = 0;
21541                            for (PackageSetting ps : allPackageSettings) {
21542                                final long status = ps.getDomainVerificationStatusForUser(userId);
21543                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21544                                        && !DEBUG_DOMAIN_VERIFICATION) {
21545                                    continue;
21546                                }
21547                                pw.println(prefix + "Package: " + ps.name);
21548                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21549                                String statusStr = IntentFilterVerificationInfo.
21550                                        getStatusStringFromValue(status);
21551                                pw.println(prefix + "Status:  " + statusStr);
21552                                pw.println();
21553                                count++;
21554                            }
21555                            if (count == 0) {
21556                                pw.println(prefix + "No configured app linkages.");
21557                                pw.println();
21558                            }
21559                        }
21560                    }
21561                }
21562            }
21563
21564            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21565                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21566            }
21567
21568            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21569                boolean printedSomething = false;
21570                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21571                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21572                        continue;
21573                    }
21574                    if (!printedSomething) {
21575                        if (dumpState.onTitlePrinted())
21576                            pw.println();
21577                        pw.println("Registered ContentProviders:");
21578                        printedSomething = true;
21579                    }
21580                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21581                    pw.print("    "); pw.println(p.toString());
21582                }
21583                printedSomething = false;
21584                for (Map.Entry<String, PackageParser.Provider> entry :
21585                        mProvidersByAuthority.entrySet()) {
21586                    PackageParser.Provider p = entry.getValue();
21587                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21588                        continue;
21589                    }
21590                    if (!printedSomething) {
21591                        if (dumpState.onTitlePrinted())
21592                            pw.println();
21593                        pw.println("ContentProvider Authorities:");
21594                        printedSomething = true;
21595                    }
21596                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21597                    pw.print("    "); pw.println(p.toString());
21598                    if (p.info != null && p.info.applicationInfo != null) {
21599                        final String appInfo = p.info.applicationInfo.toString();
21600                        pw.print("      applicationInfo="); pw.println(appInfo);
21601                    }
21602                }
21603            }
21604
21605            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21606                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21607            }
21608
21609            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21610                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21611            }
21612
21613            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21614                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21615            }
21616
21617            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21618                if (dumpState.onTitlePrinted()) pw.println();
21619                pw.println("Package Changes:");
21620                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21621                final int K = mChangedPackages.size();
21622                for (int i = 0; i < K; i++) {
21623                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21624                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21625                    final int N = changes.size();
21626                    if (N == 0) {
21627                        pw.print("    "); pw.println("No packages changed");
21628                    } else {
21629                        for (int j = 0; j < N; j++) {
21630                            final String pkgName = changes.valueAt(j);
21631                            final int sequenceNumber = changes.keyAt(j);
21632                            pw.print("    ");
21633                            pw.print("seq=");
21634                            pw.print(sequenceNumber);
21635                            pw.print(", package=");
21636                            pw.println(pkgName);
21637                        }
21638                    }
21639                }
21640            }
21641
21642            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21643                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21644            }
21645
21646            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21647                // XXX should handle packageName != null by dumping only install data that
21648                // the given package is involved with.
21649                if (dumpState.onTitlePrinted()) pw.println();
21650
21651                try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120)) {
21652                    ipw.println();
21653                    ipw.println("Frozen packages:");
21654                    ipw.increaseIndent();
21655                    if (mFrozenPackages.size() == 0) {
21656                        ipw.println("(none)");
21657                    } else {
21658                        for (int i = 0; i < mFrozenPackages.size(); i++) {
21659                            ipw.println(mFrozenPackages.valueAt(i));
21660                        }
21661                    }
21662                    ipw.decreaseIndent();
21663                }
21664            }
21665
21666            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
21667                if (dumpState.onTitlePrinted()) pw.println();
21668
21669                try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120)) {
21670                    ipw.println();
21671                    ipw.println("Loaded volumes:");
21672                    ipw.increaseIndent();
21673                    if (mLoadedVolumes.size() == 0) {
21674                        ipw.println("(none)");
21675                    } else {
21676                        for (int i = 0; i < mLoadedVolumes.size(); i++) {
21677                            ipw.println(mLoadedVolumes.valueAt(i));
21678                        }
21679                    }
21680                    ipw.decreaseIndent();
21681                }
21682            }
21683
21684            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS)
21685                    && packageName == null) {
21686                if (dumpState.onTitlePrinted()) pw.println();
21687                pw.println("Service permissions:");
21688
21689                final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator();
21690                while (filterIterator.hasNext()) {
21691                    final ServiceIntentInfo info = filterIterator.next();
21692                    final ServiceInfo serviceInfo = info.service.info;
21693                    final String permission = serviceInfo.permission;
21694                    if (permission != null) {
21695                        pw.print("    ");
21696                        pw.print(serviceInfo.getComponentName().flattenToShortString());
21697                        pw.print(": ");
21698                        pw.println(permission);
21699                    }
21700                }
21701            }
21702
21703            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21704                if (dumpState.onTitlePrinted()) pw.println();
21705                dumpDexoptStateLPr(pw, packageName);
21706            }
21707
21708            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21709                if (dumpState.onTitlePrinted()) pw.println();
21710                dumpCompilerStatsLPr(pw, packageName);
21711            }
21712
21713            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21714                if (dumpState.onTitlePrinted()) pw.println();
21715                mSettings.dumpReadMessagesLPr(pw, dumpState);
21716
21717                pw.println();
21718                pw.println("Package warning messages:");
21719                dumpCriticalInfo(pw, null);
21720            }
21721
21722            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21723                dumpCriticalInfo(pw, "msg,");
21724            }
21725        }
21726
21727        // PackageInstaller should be called outside of mPackages lock
21728        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21729            // XXX should handle packageName != null by dumping only install data that
21730            // the given package is involved with.
21731            if (dumpState.onTitlePrinted()) pw.println();
21732            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21733        }
21734    }
21735
21736    private void dumpProto(FileDescriptor fd) {
21737        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21738
21739        synchronized (mPackages) {
21740            final long requiredVerifierPackageToken =
21741                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21742            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21743            proto.write(
21744                    PackageServiceDumpProto.PackageShortProto.UID,
21745                    getPackageUid(
21746                            mRequiredVerifierPackage,
21747                            MATCH_DEBUG_TRIAGED_MISSING,
21748                            UserHandle.USER_SYSTEM));
21749            proto.end(requiredVerifierPackageToken);
21750
21751            if (mIntentFilterVerifierComponent != null) {
21752                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21753                final long verifierPackageToken =
21754                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21755                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21756                proto.write(
21757                        PackageServiceDumpProto.PackageShortProto.UID,
21758                        getPackageUid(
21759                                verifierPackageName,
21760                                MATCH_DEBUG_TRIAGED_MISSING,
21761                                UserHandle.USER_SYSTEM));
21762                proto.end(verifierPackageToken);
21763            }
21764
21765            dumpSharedLibrariesProto(proto);
21766            dumpFeaturesProto(proto);
21767            mSettings.dumpPackagesProto(proto);
21768            mSettings.dumpSharedUsersProto(proto);
21769            dumpCriticalInfo(proto);
21770        }
21771        proto.flush();
21772    }
21773
21774    private void dumpFeaturesProto(ProtoOutputStream proto) {
21775        synchronized (mAvailableFeatures) {
21776            final int count = mAvailableFeatures.size();
21777            for (int i = 0; i < count; i++) {
21778                mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
21779            }
21780        }
21781    }
21782
21783    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21784        final int count = mSharedLibraries.size();
21785        for (int i = 0; i < count; i++) {
21786            final String libName = mSharedLibraries.keyAt(i);
21787            LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21788            if (versionedLib == null) {
21789                continue;
21790            }
21791            final int versionCount = versionedLib.size();
21792            for (int j = 0; j < versionCount; j++) {
21793                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21794                final long sharedLibraryToken =
21795                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21796                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21797                final boolean isJar = (libEntry.path != null);
21798                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21799                if (isJar) {
21800                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21801                } else {
21802                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21803                }
21804                proto.end(sharedLibraryToken);
21805            }
21806        }
21807    }
21808
21809    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21810        try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ")) {
21811            ipw.println();
21812            ipw.println("Dexopt state:");
21813            ipw.increaseIndent();
21814            Collection<PackageParser.Package> packages = null;
21815            if (packageName != null) {
21816                PackageParser.Package targetPackage = mPackages.get(packageName);
21817                if (targetPackage != null) {
21818                    packages = Collections.singletonList(targetPackage);
21819                } else {
21820                    ipw.println("Unable to find package: " + packageName);
21821                    return;
21822                }
21823            } else {
21824                packages = mPackages.values();
21825            }
21826
21827            for (PackageParser.Package pkg : packages) {
21828                ipw.println("[" + pkg.packageName + "]");
21829                ipw.increaseIndent();
21830                mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
21831                        mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
21832                ipw.decreaseIndent();
21833            }
21834        }
21835    }
21836
21837    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21838        try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ")) {
21839            ipw.println();
21840            ipw.println("Compiler stats:");
21841            ipw.increaseIndent();
21842            Collection<PackageParser.Package> packages = null;
21843            if (packageName != null) {
21844                PackageParser.Package targetPackage = mPackages.get(packageName);
21845                if (targetPackage != null) {
21846                    packages = Collections.singletonList(targetPackage);
21847                } else {
21848                    ipw.println("Unable to find package: " + packageName);
21849                    return;
21850                }
21851            } else {
21852                packages = mPackages.values();
21853            }
21854
21855            for (PackageParser.Package pkg : packages) {
21856                ipw.println("[" + pkg.packageName + "]");
21857                ipw.increaseIndent();
21858
21859                CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21860                if (stats == null) {
21861                    ipw.println("(No recorded stats)");
21862                } else {
21863                    stats.dump(ipw);
21864                }
21865                ipw.decreaseIndent();
21866            }
21867        }
21868    }
21869
21870    private String dumpDomainString(String packageName) {
21871        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21872                .getList();
21873        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21874
21875        ArraySet<String> result = new ArraySet<>();
21876        if (iviList.size() > 0) {
21877            for (IntentFilterVerificationInfo ivi : iviList) {
21878                for (String host : ivi.getDomains()) {
21879                    result.add(host);
21880                }
21881            }
21882        }
21883        if (filters != null && filters.size() > 0) {
21884            for (IntentFilter filter : filters) {
21885                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21886                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21887                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21888                    result.addAll(filter.getHostsList());
21889                }
21890            }
21891        }
21892
21893        StringBuilder sb = new StringBuilder(result.size() * 16);
21894        for (String domain : result) {
21895            if (sb.length() > 0) sb.append(" ");
21896            sb.append(domain);
21897        }
21898        return sb.toString();
21899    }
21900
21901    // ------- apps on sdcard specific code -------
21902    static final boolean DEBUG_SD_INSTALL = false;
21903
21904    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21905
21906    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21907
21908    private boolean mMediaMounted = false;
21909
21910    static String getEncryptKey() {
21911        try {
21912            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21913                    SD_ENCRYPTION_KEYSTORE_NAME);
21914            if (sdEncKey == null) {
21915                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21916                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21917                if (sdEncKey == null) {
21918                    Slog.e(TAG, "Failed to create encryption keys");
21919                    return null;
21920                }
21921            }
21922            return sdEncKey;
21923        } catch (NoSuchAlgorithmException nsae) {
21924            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21925            return null;
21926        } catch (IOException ioe) {
21927            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21928            return null;
21929        }
21930    }
21931
21932    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21933            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21934        final int size = infos.size();
21935        final String[] packageNames = new String[size];
21936        final int[] packageUids = new int[size];
21937        for (int i = 0; i < size; i++) {
21938            final ApplicationInfo info = infos.get(i);
21939            packageNames[i] = info.packageName;
21940            packageUids[i] = info.uid;
21941        }
21942        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21943                finishedReceiver);
21944    }
21945
21946    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21947            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21948        sendResourcesChangedBroadcast(mediaStatus, replacing,
21949                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21950    }
21951
21952    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21953            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21954        int size = pkgList.length;
21955        if (size > 0) {
21956            // Send broadcasts here
21957            Bundle extras = new Bundle();
21958            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21959            if (uidArr != null) {
21960                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21961            }
21962            if (replacing) {
21963                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21964            }
21965            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21966                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21967            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null);
21968        }
21969    }
21970
21971    private void loadPrivatePackages(final VolumeInfo vol) {
21972        mHandler.post(new Runnable() {
21973            @Override
21974            public void run() {
21975                loadPrivatePackagesInner(vol);
21976            }
21977        });
21978    }
21979
21980    private void loadPrivatePackagesInner(VolumeInfo vol) {
21981        final String volumeUuid = vol.fsUuid;
21982        if (TextUtils.isEmpty(volumeUuid)) {
21983            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21984            return;
21985        }
21986
21987        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21988        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21989        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21990
21991        final VersionInfo ver;
21992        final List<PackageSetting> packages;
21993        synchronized (mPackages) {
21994            ver = mSettings.findOrCreateVersion(volumeUuid);
21995            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21996        }
21997
21998        for (PackageSetting ps : packages) {
21999            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
22000            synchronized (mInstallLock) {
22001                final PackageParser.Package pkg;
22002                try {
22003                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
22004                    loaded.add(pkg.applicationInfo);
22005
22006                } catch (PackageManagerException e) {
22007                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
22008                }
22009
22010                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
22011                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
22012                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
22013                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22014                }
22015            }
22016        }
22017
22018        // Reconcile app data for all started/unlocked users
22019        final StorageManager sm = mContext.getSystemService(StorageManager.class);
22020        final UserManager um = mContext.getSystemService(UserManager.class);
22021        UserManagerInternal umInternal = getUserManagerInternal();
22022        for (UserInfo user : um.getUsers()) {
22023            final int flags;
22024            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22025                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22026            } else if (umInternal.isUserRunning(user.id)) {
22027                flags = StorageManager.FLAG_STORAGE_DE;
22028            } else {
22029                continue;
22030            }
22031
22032            try {
22033                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
22034                synchronized (mInstallLock) {
22035                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
22036                }
22037            } catch (IllegalStateException e) {
22038                // Device was probably ejected, and we'll process that event momentarily
22039                Slog.w(TAG, "Failed to prepare storage: " + e);
22040            }
22041        }
22042
22043        synchronized (mPackages) {
22044            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
22045            if (sdkUpdated) {
22046                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22047                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
22048            }
22049            mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(),
22050                    mPermissionCallback);
22051
22052            // Yay, everything is now upgraded
22053            ver.forceCurrent();
22054
22055            mSettings.writeLPr();
22056        }
22057
22058        for (PackageFreezer freezer : freezers) {
22059            freezer.close();
22060        }
22061
22062        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
22063        sendResourcesChangedBroadcast(true, false, loaded, null);
22064        mLoadedVolumes.add(vol.getId());
22065    }
22066
22067    private void unloadPrivatePackages(final VolumeInfo vol) {
22068        mHandler.post(new Runnable() {
22069            @Override
22070            public void run() {
22071                unloadPrivatePackagesInner(vol);
22072            }
22073        });
22074    }
22075
22076    private void unloadPrivatePackagesInner(VolumeInfo vol) {
22077        final String volumeUuid = vol.fsUuid;
22078        if (TextUtils.isEmpty(volumeUuid)) {
22079            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
22080            return;
22081        }
22082
22083        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
22084        synchronized (mInstallLock) {
22085        synchronized (mPackages) {
22086            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
22087            for (PackageSetting ps : packages) {
22088                if (ps.pkg == null) continue;
22089
22090                final ApplicationInfo info = ps.pkg.applicationInfo;
22091                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22092                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22093
22094                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
22095                        "unloadPrivatePackagesInner")) {
22096                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
22097                            false, null)) {
22098                        unloaded.add(info);
22099                    } else {
22100                        Slog.w(TAG, "Failed to unload " + ps.codePath);
22101                    }
22102                }
22103
22104                // Try very hard to release any references to this package
22105                // so we don't risk the system server being killed due to
22106                // open FDs
22107                AttributeCache.instance().removePackage(ps.name);
22108            }
22109
22110            mSettings.writeLPr();
22111        }
22112        }
22113
22114        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
22115        sendResourcesChangedBroadcast(false, false, unloaded, null);
22116        mLoadedVolumes.remove(vol.getId());
22117
22118        // Try very hard to release any references to this path so we don't risk
22119        // the system server being killed due to open FDs
22120        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
22121
22122        for (int i = 0; i < 3; i++) {
22123            System.gc();
22124            System.runFinalization();
22125        }
22126    }
22127
22128    private void assertPackageKnown(String volumeUuid, String packageName)
22129            throws PackageManagerException {
22130        synchronized (mPackages) {
22131            // Normalize package name to handle renamed packages
22132            packageName = normalizePackageNameLPr(packageName);
22133
22134            final PackageSetting ps = mSettings.mPackages.get(packageName);
22135            if (ps == null) {
22136                throw new PackageManagerException("Package " + packageName + " is unknown");
22137            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22138                throw new PackageManagerException(
22139                        "Package " + packageName + " found on unknown volume " + volumeUuid
22140                                + "; expected volume " + ps.volumeUuid);
22141            }
22142        }
22143    }
22144
22145    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
22146            throws PackageManagerException {
22147        synchronized (mPackages) {
22148            // Normalize package name to handle renamed packages
22149            packageName = normalizePackageNameLPr(packageName);
22150
22151            final PackageSetting ps = mSettings.mPackages.get(packageName);
22152            if (ps == null) {
22153                throw new PackageManagerException("Package " + packageName + " is unknown");
22154            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22155                throw new PackageManagerException(
22156                        "Package " + packageName + " found on unknown volume " + volumeUuid
22157                                + "; expected volume " + ps.volumeUuid);
22158            } else if (!ps.getInstalled(userId)) {
22159                throw new PackageManagerException(
22160                        "Package " + packageName + " not installed for user " + userId);
22161            }
22162        }
22163    }
22164
22165    private List<String> collectAbsoluteCodePaths() {
22166        synchronized (mPackages) {
22167            List<String> codePaths = new ArrayList<>();
22168            final int packageCount = mSettings.mPackages.size();
22169            for (int i = 0; i < packageCount; i++) {
22170                final PackageSetting ps = mSettings.mPackages.valueAt(i);
22171                codePaths.add(ps.codePath.getAbsolutePath());
22172            }
22173            return codePaths;
22174        }
22175    }
22176
22177    /**
22178     * Examine all apps present on given mounted volume, and destroy apps that
22179     * aren't expected, either due to uninstallation or reinstallation on
22180     * another volume.
22181     */
22182    private void reconcileApps(String volumeUuid) {
22183        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
22184        List<File> filesToDelete = null;
22185
22186        final File[] files = FileUtils.listFilesOrEmpty(
22187                Environment.getDataAppDirectory(volumeUuid));
22188        for (File file : files) {
22189            final boolean isPackage = (isApkFile(file) || file.isDirectory())
22190                    && !PackageInstallerService.isStageName(file.getName());
22191            if (!isPackage) {
22192                // Ignore entries which are not packages
22193                continue;
22194            }
22195
22196            String absolutePath = file.getAbsolutePath();
22197
22198            boolean pathValid = false;
22199            final int absoluteCodePathCount = absoluteCodePaths.size();
22200            for (int i = 0; i < absoluteCodePathCount; i++) {
22201                String absoluteCodePath = absoluteCodePaths.get(i);
22202                if (absolutePath.startsWith(absoluteCodePath)) {
22203                    pathValid = true;
22204                    break;
22205                }
22206            }
22207
22208            if (!pathValid) {
22209                if (filesToDelete == null) {
22210                    filesToDelete = new ArrayList<>();
22211                }
22212                filesToDelete.add(file);
22213            }
22214        }
22215
22216        if (filesToDelete != null) {
22217            final int fileToDeleteCount = filesToDelete.size();
22218            for (int i = 0; i < fileToDeleteCount; i++) {
22219                File fileToDelete = filesToDelete.get(i);
22220                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22221                synchronized (mInstallLock) {
22222                    removeCodePathLI(fileToDelete);
22223                }
22224            }
22225        }
22226    }
22227
22228    /**
22229     * Reconcile all app data for the given user.
22230     * <p>
22231     * Verifies that directories exist and that ownership and labeling is
22232     * correct for all installed apps on all mounted volumes.
22233     */
22234    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22235        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22236        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22237            final String volumeUuid = vol.getFsUuid();
22238            synchronized (mInstallLock) {
22239                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22240            }
22241        }
22242    }
22243
22244    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22245            boolean migrateAppData) {
22246        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22247    }
22248
22249    /**
22250     * Reconcile all app data on given mounted volume.
22251     * <p>
22252     * Destroys app data that isn't expected, either due to uninstallation or
22253     * reinstallation on another volume.
22254     * <p>
22255     * Verifies that directories exist and that ownership and labeling is
22256     * correct for all installed apps.
22257     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22258     */
22259    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22260            boolean migrateAppData, boolean onlyCoreApps) {
22261        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22262                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22263        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22264
22265        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22266        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22267
22268        // First look for stale data that doesn't belong, and check if things
22269        // have changed since we did our last restorecon
22270        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22271            if (StorageManager.isFileEncryptedNativeOrEmulated()
22272                    && !StorageManager.isUserKeyUnlocked(userId)) {
22273                throw new RuntimeException(
22274                        "Yikes, someone asked us to reconcile CE storage while " + userId
22275                                + " was still locked; this would have caused massive data loss!");
22276            }
22277
22278            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22279            for (File file : files) {
22280                final String packageName = file.getName();
22281                try {
22282                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22283                } catch (PackageManagerException e) {
22284                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22285                    try {
22286                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22287                                StorageManager.FLAG_STORAGE_CE, 0);
22288                    } catch (InstallerException e2) {
22289                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22290                    }
22291                }
22292            }
22293        }
22294        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22295            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22296            for (File file : files) {
22297                final String packageName = file.getName();
22298                try {
22299                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22300                } catch (PackageManagerException e) {
22301                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22302                    try {
22303                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22304                                StorageManager.FLAG_STORAGE_DE, 0);
22305                    } catch (InstallerException e2) {
22306                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22307                    }
22308                }
22309            }
22310        }
22311
22312        // Ensure that data directories are ready to roll for all packages
22313        // installed for this volume and user
22314        final List<PackageSetting> packages;
22315        synchronized (mPackages) {
22316            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22317        }
22318        int preparedCount = 0;
22319        for (PackageSetting ps : packages) {
22320            final String packageName = ps.name;
22321            if (ps.pkg == null) {
22322                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22323                // TODO: might be due to legacy ASEC apps; we should circle back
22324                // and reconcile again once they're scanned
22325                continue;
22326            }
22327            // Skip non-core apps if requested
22328            if (onlyCoreApps && !ps.pkg.coreApp) {
22329                result.add(packageName);
22330                continue;
22331            }
22332
22333            if (ps.getInstalled(userId)) {
22334                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22335                preparedCount++;
22336            }
22337        }
22338
22339        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22340        return result;
22341    }
22342
22343    /**
22344     * Prepare app data for the given app just after it was installed or
22345     * upgraded. This method carefully only touches users that it's installed
22346     * for, and it forces a restorecon to handle any seinfo changes.
22347     * <p>
22348     * Verifies that directories exist and that ownership and labeling is
22349     * correct for all installed apps. If there is an ownership mismatch, it
22350     * will try recovering system apps by wiping data; third-party app data is
22351     * left intact.
22352     * <p>
22353     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22354     */
22355    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22356        final PackageSetting ps;
22357        synchronized (mPackages) {
22358            ps = mSettings.mPackages.get(pkg.packageName);
22359            mSettings.writeKernelMappingLPr(ps);
22360        }
22361
22362        final UserManager um = mContext.getSystemService(UserManager.class);
22363        UserManagerInternal umInternal = getUserManagerInternal();
22364        for (UserInfo user : um.getUsers()) {
22365            final int flags;
22366            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22367                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22368            } else if (umInternal.isUserRunning(user.id)) {
22369                flags = StorageManager.FLAG_STORAGE_DE;
22370            } else {
22371                continue;
22372            }
22373
22374            if (ps.getInstalled(user.id)) {
22375                // TODO: when user data is locked, mark that we're still dirty
22376                prepareAppDataLIF(pkg, user.id, flags);
22377            }
22378        }
22379    }
22380
22381    /**
22382     * Prepare app data for the given app.
22383     * <p>
22384     * Verifies that directories exist and that ownership and labeling is
22385     * correct for all installed apps. If there is an ownership mismatch, this
22386     * will try recovering system apps by wiping data; third-party app data is
22387     * left intact.
22388     */
22389    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22390        if (pkg == null) {
22391            Slog.wtf(TAG, "Package was null!", new Throwable());
22392            return;
22393        }
22394        prepareAppDataLeafLIF(pkg, userId, flags);
22395        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22396        for (int i = 0; i < childCount; i++) {
22397            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22398        }
22399    }
22400
22401    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22402            boolean maybeMigrateAppData) {
22403        prepareAppDataLIF(pkg, userId, flags);
22404
22405        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22406            // We may have just shuffled around app data directories, so
22407            // prepare them one more time
22408            prepareAppDataLIF(pkg, userId, flags);
22409        }
22410    }
22411
22412    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22413        if (DEBUG_APP_DATA) {
22414            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22415                    + Integer.toHexString(flags));
22416        }
22417
22418        final String volumeUuid = pkg.volumeUuid;
22419        final String packageName = pkg.packageName;
22420        final ApplicationInfo app = pkg.applicationInfo;
22421        final int appId = UserHandle.getAppId(app.uid);
22422
22423        Preconditions.checkNotNull(app.seInfo);
22424
22425        long ceDataInode = -1;
22426        try {
22427            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22428                    appId, app.seInfo, app.targetSdkVersion);
22429        } catch (InstallerException e) {
22430            if (app.isSystemApp()) {
22431                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22432                        + ", but trying to recover: " + e);
22433                destroyAppDataLeafLIF(pkg, userId, flags);
22434                try {
22435                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22436                            appId, app.seInfo, app.targetSdkVersion);
22437                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22438                } catch (InstallerException e2) {
22439                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22440                }
22441            } else {
22442                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22443            }
22444        }
22445        // Prepare the application profiles only for upgrades and first boot (so that we don't
22446        // repeat the same operation at each boot).
22447        // We only have to cover the upgrade and first boot here because for app installs we
22448        // prepare the profiles before invoking dexopt (in installPackageLI).
22449        //
22450        // We also have to cover non system users because we do not call the usual install package
22451        // methods for them.
22452        if (mIsUpgrade || mFirstBoot || (userId != UserHandle.USER_SYSTEM)) {
22453            mArtManagerService.prepareAppProfiles(pkg, userId);
22454        }
22455
22456        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22457            // TODO: mark this structure as dirty so we persist it!
22458            synchronized (mPackages) {
22459                final PackageSetting ps = mSettings.mPackages.get(packageName);
22460                if (ps != null) {
22461                    ps.setCeDataInode(ceDataInode, userId);
22462                }
22463            }
22464        }
22465
22466        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22467    }
22468
22469    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22470        if (pkg == null) {
22471            Slog.wtf(TAG, "Package was null!", new Throwable());
22472            return;
22473        }
22474        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22475        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22476        for (int i = 0; i < childCount; i++) {
22477            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22478        }
22479    }
22480
22481    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22482        final String volumeUuid = pkg.volumeUuid;
22483        final String packageName = pkg.packageName;
22484        final ApplicationInfo app = pkg.applicationInfo;
22485
22486        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22487            // Create a native library symlink only if we have native libraries
22488            // and if the native libraries are 32 bit libraries. We do not provide
22489            // this symlink for 64 bit libraries.
22490            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22491                final String nativeLibPath = app.nativeLibraryDir;
22492                try {
22493                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22494                            nativeLibPath, userId);
22495                } catch (InstallerException e) {
22496                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22497                }
22498            }
22499        }
22500    }
22501
22502    /**
22503     * For system apps on non-FBE devices, this method migrates any existing
22504     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22505     * requested by the app.
22506     */
22507    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22508        if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated()
22509                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22510            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22511                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22512            try {
22513                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22514                        storageTarget);
22515            } catch (InstallerException e) {
22516                logCriticalInfo(Log.WARN,
22517                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22518            }
22519            return true;
22520        } else {
22521            return false;
22522        }
22523    }
22524
22525    public PackageFreezer freezePackage(String packageName, String killReason) {
22526        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22527    }
22528
22529    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22530        return new PackageFreezer(packageName, userId, killReason);
22531    }
22532
22533    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22534            String killReason) {
22535        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22536    }
22537
22538    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22539            String killReason) {
22540        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22541            return new PackageFreezer();
22542        } else {
22543            return freezePackage(packageName, userId, killReason);
22544        }
22545    }
22546
22547    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22548            String killReason) {
22549        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22550    }
22551
22552    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22553            String killReason) {
22554        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22555            return new PackageFreezer();
22556        } else {
22557            return freezePackage(packageName, userId, killReason);
22558        }
22559    }
22560
22561    /**
22562     * Class that freezes and kills the given package upon creation, and
22563     * unfreezes it upon closing. This is typically used when doing surgery on
22564     * app code/data to prevent the app from running while you're working.
22565     */
22566    private class PackageFreezer implements AutoCloseable {
22567        private final String mPackageName;
22568        private final PackageFreezer[] mChildren;
22569
22570        private final boolean mWeFroze;
22571
22572        private final AtomicBoolean mClosed = new AtomicBoolean();
22573        private final CloseGuard mCloseGuard = CloseGuard.get();
22574
22575        /**
22576         * Create and return a stub freezer that doesn't actually do anything,
22577         * typically used when someone requested
22578         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22579         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22580         */
22581        public PackageFreezer() {
22582            mPackageName = null;
22583            mChildren = null;
22584            mWeFroze = false;
22585            mCloseGuard.open("close");
22586        }
22587
22588        public PackageFreezer(String packageName, int userId, String killReason) {
22589            synchronized (mPackages) {
22590                mPackageName = packageName;
22591                mWeFroze = mFrozenPackages.add(mPackageName);
22592
22593                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22594                if (ps != null) {
22595                    killApplication(ps.name, ps.appId, userId, killReason);
22596                }
22597
22598                final PackageParser.Package p = mPackages.get(packageName);
22599                if (p != null && p.childPackages != null) {
22600                    final int N = p.childPackages.size();
22601                    mChildren = new PackageFreezer[N];
22602                    for (int i = 0; i < N; i++) {
22603                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22604                                userId, killReason);
22605                    }
22606                } else {
22607                    mChildren = null;
22608                }
22609            }
22610            mCloseGuard.open("close");
22611        }
22612
22613        @Override
22614        protected void finalize() throws Throwable {
22615            try {
22616                if (mCloseGuard != null) {
22617                    mCloseGuard.warnIfOpen();
22618                }
22619
22620                close();
22621            } finally {
22622                super.finalize();
22623            }
22624        }
22625
22626        @Override
22627        public void close() {
22628            mCloseGuard.close();
22629            if (mClosed.compareAndSet(false, true)) {
22630                synchronized (mPackages) {
22631                    if (mWeFroze) {
22632                        mFrozenPackages.remove(mPackageName);
22633                    }
22634
22635                    if (mChildren != null) {
22636                        for (PackageFreezer freezer : mChildren) {
22637                            freezer.close();
22638                        }
22639                    }
22640                }
22641            }
22642        }
22643    }
22644
22645    /**
22646     * Verify that given package is currently frozen.
22647     */
22648    private void checkPackageFrozen(String packageName) {
22649        synchronized (mPackages) {
22650            if (!mFrozenPackages.contains(packageName)) {
22651                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22652            }
22653        }
22654    }
22655
22656    @Override
22657    public int movePackage(final String packageName, final String volumeUuid) {
22658        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22659
22660        final int callingUid = Binder.getCallingUid();
22661        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
22662        final int moveId = mNextMoveId.getAndIncrement();
22663        mHandler.post(new Runnable() {
22664            @Override
22665            public void run() {
22666                try {
22667                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
22668                } catch (PackageManagerException e) {
22669                    Slog.w(TAG, "Failed to move " + packageName, e);
22670                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
22671                }
22672            }
22673        });
22674        return moveId;
22675    }
22676
22677    private void movePackageInternal(final String packageName, final String volumeUuid,
22678            final int moveId, final int callingUid, UserHandle user)
22679                    throws PackageManagerException {
22680        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22681        final PackageManager pm = mContext.getPackageManager();
22682
22683        final boolean currentAsec;
22684        final String currentVolumeUuid;
22685        final File codeFile;
22686        final String installerPackageName;
22687        final String packageAbiOverride;
22688        final int appId;
22689        final String seinfo;
22690        final String label;
22691        final int targetSdkVersion;
22692        final PackageFreezer freezer;
22693        final int[] installedUserIds;
22694
22695        // reader
22696        synchronized (mPackages) {
22697            final PackageParser.Package pkg = mPackages.get(packageName);
22698            final PackageSetting ps = mSettings.mPackages.get(packageName);
22699            if (pkg == null
22700                    || ps == null
22701                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
22702                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22703            }
22704            if (pkg.applicationInfo.isSystemApp()) {
22705                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22706                        "Cannot move system application");
22707            }
22708
22709            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22710            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22711                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22712            if (isInternalStorage && !allow3rdPartyOnInternal) {
22713                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22714                        "3rd party apps are not allowed on internal storage");
22715            }
22716
22717            if (pkg.applicationInfo.isExternalAsec()) {
22718                currentAsec = true;
22719                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22720            } else if (pkg.applicationInfo.isForwardLocked()) {
22721                currentAsec = true;
22722                currentVolumeUuid = "forward_locked";
22723            } else {
22724                currentAsec = false;
22725                currentVolumeUuid = ps.volumeUuid;
22726
22727                final File probe = new File(pkg.codePath);
22728                final File probeOat = new File(probe, "oat");
22729                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22730                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22731                            "Move only supported for modern cluster style installs");
22732                }
22733            }
22734
22735            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22736                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22737                        "Package already moved to " + volumeUuid);
22738            }
22739            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22740                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22741                        "Device admin cannot be moved");
22742            }
22743
22744            if (mFrozenPackages.contains(packageName)) {
22745                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22746                        "Failed to move already frozen package");
22747            }
22748
22749            codeFile = new File(pkg.codePath);
22750            installerPackageName = ps.installerPackageName;
22751            packageAbiOverride = ps.cpuAbiOverrideString;
22752            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22753            seinfo = pkg.applicationInfo.seInfo;
22754            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22755            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22756            freezer = freezePackage(packageName, "movePackageInternal");
22757            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22758        }
22759
22760        final Bundle extras = new Bundle();
22761        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22762        extras.putString(Intent.EXTRA_TITLE, label);
22763        mMoveCallbacks.notifyCreated(moveId, extras);
22764
22765        int installFlags;
22766        final boolean moveCompleteApp;
22767        final File measurePath;
22768
22769        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22770            installFlags = INSTALL_INTERNAL;
22771            moveCompleteApp = !currentAsec;
22772            measurePath = Environment.getDataAppDirectory(volumeUuid);
22773        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22774            installFlags = INSTALL_EXTERNAL;
22775            moveCompleteApp = false;
22776            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22777        } else {
22778            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22779            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22780                    || !volume.isMountedWritable()) {
22781                freezer.close();
22782                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22783                        "Move location not mounted private volume");
22784            }
22785
22786            Preconditions.checkState(!currentAsec);
22787
22788            installFlags = INSTALL_INTERNAL;
22789            moveCompleteApp = true;
22790            measurePath = Environment.getDataAppDirectory(volumeUuid);
22791        }
22792
22793        // If we're moving app data around, we need all the users unlocked
22794        if (moveCompleteApp) {
22795            for (int userId : installedUserIds) {
22796                if (StorageManager.isFileEncryptedNativeOrEmulated()
22797                        && !StorageManager.isUserKeyUnlocked(userId)) {
22798                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
22799                            "User " + userId + " must be unlocked");
22800                }
22801            }
22802        }
22803
22804        final PackageStats stats = new PackageStats(null, -1);
22805        synchronized (mInstaller) {
22806            for (int userId : installedUserIds) {
22807                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22808                    freezer.close();
22809                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22810                            "Failed to measure package size");
22811                }
22812            }
22813        }
22814
22815        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22816                + stats.dataSize);
22817
22818        final long startFreeBytes = measurePath.getUsableSpace();
22819        final long sizeBytes;
22820        if (moveCompleteApp) {
22821            sizeBytes = stats.codeSize + stats.dataSize;
22822        } else {
22823            sizeBytes = stats.codeSize;
22824        }
22825
22826        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22827            freezer.close();
22828            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22829                    "Not enough free space to move");
22830        }
22831
22832        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22833
22834        final CountDownLatch installedLatch = new CountDownLatch(1);
22835        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22836            @Override
22837            public void onUserActionRequired(Intent intent) throws RemoteException {
22838                throw new IllegalStateException();
22839            }
22840
22841            @Override
22842            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22843                    Bundle extras) throws RemoteException {
22844                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22845                        + PackageManager.installStatusToString(returnCode, msg));
22846
22847                installedLatch.countDown();
22848                freezer.close();
22849
22850                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22851                switch (status) {
22852                    case PackageInstaller.STATUS_SUCCESS:
22853                        mMoveCallbacks.notifyStatusChanged(moveId,
22854                                PackageManager.MOVE_SUCCEEDED);
22855                        break;
22856                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22857                        mMoveCallbacks.notifyStatusChanged(moveId,
22858                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22859                        break;
22860                    default:
22861                        mMoveCallbacks.notifyStatusChanged(moveId,
22862                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22863                        break;
22864                }
22865            }
22866        };
22867
22868        final MoveInfo move;
22869        if (moveCompleteApp) {
22870            // Kick off a thread to report progress estimates
22871            new Thread() {
22872                @Override
22873                public void run() {
22874                    while (true) {
22875                        try {
22876                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22877                                break;
22878                            }
22879                        } catch (InterruptedException ignored) {
22880                        }
22881
22882                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22883                        final int progress = 10 + (int) MathUtils.constrain(
22884                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22885                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22886                    }
22887                }
22888            }.start();
22889
22890            final String dataAppName = codeFile.getName();
22891            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22892                    dataAppName, appId, seinfo, targetSdkVersion);
22893        } else {
22894            move = null;
22895        }
22896
22897        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22898
22899        final Message msg = mHandler.obtainMessage(INIT_COPY);
22900        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22901        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22902                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22903                packageAbiOverride, null /*grantedPermissions*/,
22904                PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN);
22905        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22906        msg.obj = params;
22907
22908        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22909                System.identityHashCode(msg.obj));
22910        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22911                System.identityHashCode(msg.obj));
22912
22913        mHandler.sendMessage(msg);
22914    }
22915
22916    @Override
22917    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22918        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22919
22920        final int realMoveId = mNextMoveId.getAndIncrement();
22921        final Bundle extras = new Bundle();
22922        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22923        mMoveCallbacks.notifyCreated(realMoveId, extras);
22924
22925        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22926            @Override
22927            public void onCreated(int moveId, Bundle extras) {
22928                // Ignored
22929            }
22930
22931            @Override
22932            public void onStatusChanged(int moveId, int status, long estMillis) {
22933                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22934            }
22935        };
22936
22937        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22938        storage.setPrimaryStorageUuid(volumeUuid, callback);
22939        return realMoveId;
22940    }
22941
22942    @Override
22943    public int getMoveStatus(int moveId) {
22944        mContext.enforceCallingOrSelfPermission(
22945                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22946        return mMoveCallbacks.mLastStatus.get(moveId);
22947    }
22948
22949    @Override
22950    public void registerMoveCallback(IPackageMoveObserver callback) {
22951        mContext.enforceCallingOrSelfPermission(
22952                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22953        mMoveCallbacks.register(callback);
22954    }
22955
22956    @Override
22957    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22958        mContext.enforceCallingOrSelfPermission(
22959                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22960        mMoveCallbacks.unregister(callback);
22961    }
22962
22963    @Override
22964    public boolean setInstallLocation(int loc) {
22965        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22966                null);
22967        if (getInstallLocation() == loc) {
22968            return true;
22969        }
22970        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22971                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22972            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22973                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22974            return true;
22975        }
22976        return false;
22977   }
22978
22979    @Override
22980    public int getInstallLocation() {
22981        // allow instant app access
22982        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22983                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22984                PackageHelper.APP_INSTALL_AUTO);
22985    }
22986
22987    /** Called by UserManagerService */
22988    void cleanUpUser(UserManagerService userManager, int userHandle) {
22989        synchronized (mPackages) {
22990            mDirtyUsers.remove(userHandle);
22991            mUserNeedsBadging.delete(userHandle);
22992            mSettings.removeUserLPw(userHandle);
22993            mPendingBroadcasts.remove(userHandle);
22994            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22995            removeUnusedPackagesLPw(userManager, userHandle);
22996        }
22997    }
22998
22999    /**
23000     * We're removing userHandle and would like to remove any downloaded packages
23001     * that are no longer in use by any other user.
23002     * @param userHandle the user being removed
23003     */
23004    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
23005        final boolean DEBUG_CLEAN_APKS = false;
23006        int [] users = userManager.getUserIds();
23007        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
23008        while (psit.hasNext()) {
23009            PackageSetting ps = psit.next();
23010            if (ps.pkg == null) {
23011                continue;
23012            }
23013            final String packageName = ps.pkg.packageName;
23014            // Skip over if system app
23015            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23016                continue;
23017            }
23018            if (DEBUG_CLEAN_APKS) {
23019                Slog.i(TAG, "Checking package " + packageName);
23020            }
23021            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
23022            if (keep) {
23023                if (DEBUG_CLEAN_APKS) {
23024                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
23025                }
23026            } else {
23027                for (int i = 0; i < users.length; i++) {
23028                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
23029                        keep = true;
23030                        if (DEBUG_CLEAN_APKS) {
23031                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
23032                                    + users[i]);
23033                        }
23034                        break;
23035                    }
23036                }
23037            }
23038            if (!keep) {
23039                if (DEBUG_CLEAN_APKS) {
23040                    Slog.i(TAG, "  Removing package " + packageName);
23041                }
23042                mHandler.post(new Runnable() {
23043                    public void run() {
23044                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23045                                userHandle, 0);
23046                    } //end run
23047                });
23048            }
23049        }
23050    }
23051
23052    /** Called by UserManagerService */
23053    void createNewUser(int userId, String[] disallowedPackages) {
23054        synchronized (mInstallLock) {
23055            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
23056        }
23057        synchronized (mPackages) {
23058            scheduleWritePackageRestrictionsLocked(userId);
23059            scheduleWritePackageListLocked(userId);
23060            applyFactoryDefaultBrowserLPw(userId);
23061            primeDomainVerificationsLPw(userId);
23062        }
23063    }
23064
23065    void onNewUserCreated(final int userId) {
23066        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
23067        synchronized(mPackages) {
23068            // If permission review for legacy apps is required, we represent
23069            // dagerous permissions for such apps as always granted runtime
23070            // permissions to keep per user flag state whether review is needed.
23071            // Hence, if a new user is added we have to propagate dangerous
23072            // permission grants for these legacy apps.
23073            if (mSettings.mPermissions.mPermissionReviewRequired) {
23074// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG
23075                mPermissionManager.updateAllPermissions(
23076                        StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(),
23077                        mPermissionCallback);
23078            }
23079        }
23080    }
23081
23082    @Override
23083    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
23084        mContext.enforceCallingOrSelfPermission(
23085                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
23086                "Only package verification agents can read the verifier device identity");
23087
23088        synchronized (mPackages) {
23089            return mSettings.getVerifierDeviceIdentityLPw();
23090        }
23091    }
23092
23093    @Override
23094    public void setPermissionEnforced(String permission, boolean enforced) {
23095        // TODO: Now that we no longer change GID for storage, this should to away.
23096        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
23097                "setPermissionEnforced");
23098        if (READ_EXTERNAL_STORAGE.equals(permission)) {
23099            synchronized (mPackages) {
23100                if (mSettings.mReadExternalStorageEnforced == null
23101                        || mSettings.mReadExternalStorageEnforced != enforced) {
23102                    mSettings.mReadExternalStorageEnforced =
23103                            enforced ? Boolean.TRUE : Boolean.FALSE;
23104                    mSettings.writeLPr();
23105                }
23106            }
23107            // kill any non-foreground processes so we restart them and
23108            // grant/revoke the GID.
23109            final IActivityManager am = ActivityManager.getService();
23110            if (am != null) {
23111                final long token = Binder.clearCallingIdentity();
23112                try {
23113                    am.killProcessesBelowForeground("setPermissionEnforcement");
23114                } catch (RemoteException e) {
23115                } finally {
23116                    Binder.restoreCallingIdentity(token);
23117                }
23118            }
23119        } else {
23120            throw new IllegalArgumentException("No selective enforcement for " + permission);
23121        }
23122    }
23123
23124    @Override
23125    @Deprecated
23126    public boolean isPermissionEnforced(String permission) {
23127        // allow instant applications
23128        return true;
23129    }
23130
23131    @Override
23132    public boolean isStorageLow() {
23133        // allow instant applications
23134        final long token = Binder.clearCallingIdentity();
23135        try {
23136            final DeviceStorageMonitorInternal
23137                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
23138            if (dsm != null) {
23139                return dsm.isMemoryLow();
23140            } else {
23141                return false;
23142            }
23143        } finally {
23144            Binder.restoreCallingIdentity(token);
23145        }
23146    }
23147
23148    @Override
23149    public IPackageInstaller getPackageInstaller() {
23150        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23151            return null;
23152        }
23153        return mInstallerService;
23154    }
23155
23156    @Override
23157    public IArtManager getArtManager() {
23158        return mArtManagerService;
23159    }
23160
23161    private boolean userNeedsBadging(int userId) {
23162        int index = mUserNeedsBadging.indexOfKey(userId);
23163        if (index < 0) {
23164            final UserInfo userInfo;
23165            final long token = Binder.clearCallingIdentity();
23166            try {
23167                userInfo = sUserManager.getUserInfo(userId);
23168            } finally {
23169                Binder.restoreCallingIdentity(token);
23170            }
23171            final boolean b;
23172            if (userInfo != null && userInfo.isManagedProfile()) {
23173                b = true;
23174            } else {
23175                b = false;
23176            }
23177            mUserNeedsBadging.put(userId, b);
23178            return b;
23179        }
23180        return mUserNeedsBadging.valueAt(index);
23181    }
23182
23183    @Override
23184    public KeySet getKeySetByAlias(String packageName, String alias) {
23185        if (packageName == null || alias == null) {
23186            return null;
23187        }
23188        synchronized(mPackages) {
23189            final PackageParser.Package pkg = mPackages.get(packageName);
23190            if (pkg == null) {
23191                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23192                throw new IllegalArgumentException("Unknown package: " + packageName);
23193            }
23194            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23195            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
23196                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
23197                throw new IllegalArgumentException("Unknown package: " + packageName);
23198            }
23199            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23200            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
23201        }
23202    }
23203
23204    @Override
23205    public KeySet getSigningKeySet(String packageName) {
23206        if (packageName == null) {
23207            return null;
23208        }
23209        synchronized(mPackages) {
23210            final int callingUid = Binder.getCallingUid();
23211            final int callingUserId = UserHandle.getUserId(callingUid);
23212            final PackageParser.Package pkg = mPackages.get(packageName);
23213            if (pkg == null) {
23214                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23215                throw new IllegalArgumentException("Unknown package: " + packageName);
23216            }
23217            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23218            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
23219                // filter and pretend the package doesn't exist
23220                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
23221                        + ", uid:" + callingUid);
23222                throw new IllegalArgumentException("Unknown package: " + packageName);
23223            }
23224            if (pkg.applicationInfo.uid != callingUid
23225                    && Process.SYSTEM_UID != callingUid) {
23226                throw new SecurityException("May not access signing KeySet of other apps.");
23227            }
23228            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23229            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
23230        }
23231    }
23232
23233    @Override
23234    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
23235        final int callingUid = Binder.getCallingUid();
23236        if (getInstantAppPackageName(callingUid) != null) {
23237            return false;
23238        }
23239        if (packageName == null || ks == null) {
23240            return false;
23241        }
23242        synchronized(mPackages) {
23243            final PackageParser.Package pkg = mPackages.get(packageName);
23244            if (pkg == null
23245                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23246                            UserHandle.getUserId(callingUid))) {
23247                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23248                throw new IllegalArgumentException("Unknown package: " + packageName);
23249            }
23250            IBinder ksh = ks.getToken();
23251            if (ksh instanceof KeySetHandle) {
23252                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23253                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23254            }
23255            return false;
23256        }
23257    }
23258
23259    @Override
23260    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23261        final int callingUid = Binder.getCallingUid();
23262        if (getInstantAppPackageName(callingUid) != null) {
23263            return false;
23264        }
23265        if (packageName == null || ks == null) {
23266            return false;
23267        }
23268        synchronized(mPackages) {
23269            final PackageParser.Package pkg = mPackages.get(packageName);
23270            if (pkg == null
23271                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23272                            UserHandle.getUserId(callingUid))) {
23273                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23274                throw new IllegalArgumentException("Unknown package: " + packageName);
23275            }
23276            IBinder ksh = ks.getToken();
23277            if (ksh instanceof KeySetHandle) {
23278                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23279                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23280            }
23281            return false;
23282        }
23283    }
23284
23285    private void deletePackageIfUnusedLPr(final String packageName) {
23286        PackageSetting ps = mSettings.mPackages.get(packageName);
23287        if (ps == null) {
23288            return;
23289        }
23290        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23291            // TODO Implement atomic delete if package is unused
23292            // It is currently possible that the package will be deleted even if it is installed
23293            // after this method returns.
23294            mHandler.post(new Runnable() {
23295                public void run() {
23296                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23297                            0, PackageManager.DELETE_ALL_USERS);
23298                }
23299            });
23300        }
23301    }
23302
23303    /**
23304     * Check and throw if the given before/after packages would be considered a
23305     * downgrade.
23306     */
23307    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23308            throws PackageManagerException {
23309        if (after.getLongVersionCode() < before.getLongVersionCode()) {
23310            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23311                    "Update version code " + after.versionCode + " is older than current "
23312                    + before.getLongVersionCode());
23313        } else if (after.getLongVersionCode() == before.getLongVersionCode()) {
23314            if (after.baseRevisionCode < before.baseRevisionCode) {
23315                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23316                        "Update base revision code " + after.baseRevisionCode
23317                        + " is older than current " + before.baseRevisionCode);
23318            }
23319
23320            if (!ArrayUtils.isEmpty(after.splitNames)) {
23321                for (int i = 0; i < after.splitNames.length; i++) {
23322                    final String splitName = after.splitNames[i];
23323                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23324                    if (j != -1) {
23325                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23326                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23327                                    "Update split " + splitName + " revision code "
23328                                    + after.splitRevisionCodes[i] + " is older than current "
23329                                    + before.splitRevisionCodes[j]);
23330                        }
23331                    }
23332                }
23333            }
23334        }
23335    }
23336
23337    private static class MoveCallbacks extends Handler {
23338        private static final int MSG_CREATED = 1;
23339        private static final int MSG_STATUS_CHANGED = 2;
23340
23341        private final RemoteCallbackList<IPackageMoveObserver>
23342                mCallbacks = new RemoteCallbackList<>();
23343
23344        private final SparseIntArray mLastStatus = new SparseIntArray();
23345
23346        public MoveCallbacks(Looper looper) {
23347            super(looper);
23348        }
23349
23350        public void register(IPackageMoveObserver callback) {
23351            mCallbacks.register(callback);
23352        }
23353
23354        public void unregister(IPackageMoveObserver callback) {
23355            mCallbacks.unregister(callback);
23356        }
23357
23358        @Override
23359        public void handleMessage(Message msg) {
23360            final SomeArgs args = (SomeArgs) msg.obj;
23361            final int n = mCallbacks.beginBroadcast();
23362            for (int i = 0; i < n; i++) {
23363                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23364                try {
23365                    invokeCallback(callback, msg.what, args);
23366                } catch (RemoteException ignored) {
23367                }
23368            }
23369            mCallbacks.finishBroadcast();
23370            args.recycle();
23371        }
23372
23373        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23374                throws RemoteException {
23375            switch (what) {
23376                case MSG_CREATED: {
23377                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23378                    break;
23379                }
23380                case MSG_STATUS_CHANGED: {
23381                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23382                    break;
23383                }
23384            }
23385        }
23386
23387        private void notifyCreated(int moveId, Bundle extras) {
23388            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23389
23390            final SomeArgs args = SomeArgs.obtain();
23391            args.argi1 = moveId;
23392            args.arg2 = extras;
23393            obtainMessage(MSG_CREATED, args).sendToTarget();
23394        }
23395
23396        private void notifyStatusChanged(int moveId, int status) {
23397            notifyStatusChanged(moveId, status, -1);
23398        }
23399
23400        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23401            Slog.v(TAG, "Move " + moveId + " status " + status);
23402
23403            final SomeArgs args = SomeArgs.obtain();
23404            args.argi1 = moveId;
23405            args.argi2 = status;
23406            args.arg3 = estMillis;
23407            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23408
23409            synchronized (mLastStatus) {
23410                mLastStatus.put(moveId, status);
23411            }
23412        }
23413    }
23414
23415    private final static class OnPermissionChangeListeners extends Handler {
23416        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23417
23418        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23419                new RemoteCallbackList<>();
23420
23421        public OnPermissionChangeListeners(Looper looper) {
23422            super(looper);
23423        }
23424
23425        @Override
23426        public void handleMessage(Message msg) {
23427            switch (msg.what) {
23428                case MSG_ON_PERMISSIONS_CHANGED: {
23429                    final int uid = msg.arg1;
23430                    handleOnPermissionsChanged(uid);
23431                } break;
23432            }
23433        }
23434
23435        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23436            mPermissionListeners.register(listener);
23437
23438        }
23439
23440        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23441            mPermissionListeners.unregister(listener);
23442        }
23443
23444        public void onPermissionsChanged(int uid) {
23445            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23446                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23447            }
23448        }
23449
23450        private void handleOnPermissionsChanged(int uid) {
23451            final int count = mPermissionListeners.beginBroadcast();
23452            try {
23453                for (int i = 0; i < count; i++) {
23454                    IOnPermissionsChangeListener callback = mPermissionListeners
23455                            .getBroadcastItem(i);
23456                    try {
23457                        callback.onPermissionsChanged(uid);
23458                    } catch (RemoteException e) {
23459                        Log.e(TAG, "Permission listener is dead", e);
23460                    }
23461                }
23462            } finally {
23463                mPermissionListeners.finishBroadcast();
23464            }
23465        }
23466    }
23467
23468    private class PackageManagerNative extends IPackageManagerNative.Stub {
23469        @Override
23470        public String[] getNamesForUids(int[] uids) throws RemoteException {
23471            final String[] results = PackageManagerService.this.getNamesForUids(uids);
23472            // massage results so they can be parsed by the native binder
23473            for (int i = results.length - 1; i >= 0; --i) {
23474                if (results[i] == null) {
23475                    results[i] = "";
23476                }
23477            }
23478            return results;
23479        }
23480
23481        // NB: this differentiates between preloads and sideloads
23482        @Override
23483        public String getInstallerForPackage(String packageName) throws RemoteException {
23484            final String installerName = getInstallerPackageName(packageName);
23485            if (!TextUtils.isEmpty(installerName)) {
23486                return installerName;
23487            }
23488            // differentiate between preload and sideload
23489            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23490            ApplicationInfo appInfo = getApplicationInfo(packageName,
23491                                    /*flags*/ 0,
23492                                    /*userId*/ callingUser);
23493            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23494                return "preload";
23495            }
23496            return "";
23497        }
23498
23499        @Override
23500        public long getVersionCodeForPackage(String packageName) throws RemoteException {
23501            try {
23502                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23503                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
23504                if (pInfo != null) {
23505                    return pInfo.getLongVersionCode();
23506                }
23507            } catch (Exception e) {
23508            }
23509            return 0;
23510        }
23511    }
23512
23513    private class PackageManagerInternalImpl extends PackageManagerInternal {
23514        @Override
23515        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
23516                int flagValues, int userId) {
23517            PackageManagerService.this.updatePermissionFlags(
23518                    permName, packageName, flagMask, flagValues, userId);
23519        }
23520
23521        @Override
23522        public boolean isDataRestoreSafe(byte[] restoringFromSigHash, String packageName) {
23523            SigningDetails sd = getSigningDetails(packageName);
23524            if (sd == null) {
23525                return false;
23526            }
23527            return sd.hasSha256Certificate(restoringFromSigHash,
23528                    SigningDetails.CertCapabilities.INSTALLED_DATA);
23529        }
23530
23531        @Override
23532        public boolean isDataRestoreSafe(Signature restoringFromSig, String packageName) {
23533            SigningDetails sd = getSigningDetails(packageName);
23534            if (sd == null) {
23535                return false;
23536            }
23537            return sd.hasCertificate(restoringFromSig,
23538                    SigningDetails.CertCapabilities.INSTALLED_DATA);
23539        }
23540
23541        private SigningDetails getSigningDetails(@NonNull String packageName) {
23542            synchronized (mPackages) {
23543                PackageParser.Package p = mPackages.get(packageName);
23544                if (p == null) {
23545                    return null;
23546                }
23547                return p.mSigningDetails;
23548            }
23549        }
23550
23551        @Override
23552        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
23553            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
23554        }
23555
23556        @Override
23557        public boolean isInstantApp(String packageName, int userId) {
23558            return PackageManagerService.this.isInstantApp(packageName, userId);
23559        }
23560
23561        @Override
23562        public String getInstantAppPackageName(int uid) {
23563            return PackageManagerService.this.getInstantAppPackageName(uid);
23564        }
23565
23566        @Override
23567        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
23568            synchronized (mPackages) {
23569                return PackageManagerService.this.filterAppAccessLPr(
23570                        (PackageSetting) pkg.mExtras, callingUid, userId);
23571            }
23572        }
23573
23574        @Override
23575        public PackageParser.Package getPackage(String packageName) {
23576            synchronized (mPackages) {
23577                packageName = resolveInternalPackageNameLPr(
23578                        packageName, PackageManager.VERSION_CODE_HIGHEST);
23579                return mPackages.get(packageName);
23580            }
23581        }
23582
23583        @Override
23584        public PackageList getPackageList(PackageListObserver observer) {
23585            synchronized (mPackages) {
23586                final int N = mPackages.size();
23587                final ArrayList<String> list = new ArrayList<>(N);
23588                for (int i = 0; i < N; i++) {
23589                    list.add(mPackages.keyAt(i));
23590                }
23591                final PackageList packageList = new PackageList(list, observer);
23592                if (observer != null) {
23593                    mPackageListObservers.add(packageList);
23594                }
23595                return packageList;
23596            }
23597        }
23598
23599        @Override
23600        public void removePackageListObserver(PackageListObserver observer) {
23601            synchronized (mPackages) {
23602                mPackageListObservers.remove(observer);
23603            }
23604        }
23605
23606        @Override
23607        public PackageParser.Package getDisabledPackage(String packageName) {
23608            synchronized (mPackages) {
23609                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
23610                return (ps != null) ? ps.pkg : null;
23611            }
23612        }
23613
23614        @Override
23615        public String getKnownPackageName(int knownPackage, int userId) {
23616            switch(knownPackage) {
23617                case PackageManagerInternal.PACKAGE_BROWSER:
23618                    return getDefaultBrowserPackageName(userId);
23619                case PackageManagerInternal.PACKAGE_INSTALLER:
23620                    return mRequiredInstallerPackage;
23621                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
23622                    return mSetupWizardPackage;
23623                case PackageManagerInternal.PACKAGE_SYSTEM:
23624                    return "android";
23625                case PackageManagerInternal.PACKAGE_VERIFIER:
23626                    return mRequiredVerifierPackage;
23627                case PackageManagerInternal.PACKAGE_SYSTEM_TEXT_CLASSIFIER:
23628                    return mSystemTextClassifierPackage;
23629            }
23630            return null;
23631        }
23632
23633        @Override
23634        public boolean isResolveActivityComponent(ComponentInfo component) {
23635            return mResolveActivity.packageName.equals(component.packageName)
23636                    && mResolveActivity.name.equals(component.name);
23637        }
23638
23639        @Override
23640        public void setLocationPackagesProvider(PackagesProvider provider) {
23641            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
23642        }
23643
23644        @Override
23645        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23646            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
23647        }
23648
23649        @Override
23650        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23651            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
23652        }
23653
23654        @Override
23655        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23656            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
23657        }
23658
23659        @Override
23660        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23661            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
23662        }
23663
23664        @Override
23665        public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) {
23666            mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider);
23667        }
23668
23669        @Override
23670        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23671            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
23672        }
23673
23674        @Override
23675        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23676            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
23677        }
23678
23679        @Override
23680        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23681            synchronized (mPackages) {
23682                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23683            }
23684            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
23685        }
23686
23687        @Override
23688        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23689            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
23690                    packageName, userId);
23691        }
23692
23693        @Override
23694        public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) {
23695            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp(
23696                    packageName, userId);
23697        }
23698
23699        @Override
23700        public void setKeepUninstalledPackages(final List<String> packageList) {
23701            Preconditions.checkNotNull(packageList);
23702            List<String> removedFromList = null;
23703            synchronized (mPackages) {
23704                if (mKeepUninstalledPackages != null) {
23705                    final int packagesCount = mKeepUninstalledPackages.size();
23706                    for (int i = 0; i < packagesCount; i++) {
23707                        String oldPackage = mKeepUninstalledPackages.get(i);
23708                        if (packageList != null && packageList.contains(oldPackage)) {
23709                            continue;
23710                        }
23711                        if (removedFromList == null) {
23712                            removedFromList = new ArrayList<>();
23713                        }
23714                        removedFromList.add(oldPackage);
23715                    }
23716                }
23717                mKeepUninstalledPackages = new ArrayList<>(packageList);
23718                if (removedFromList != null) {
23719                    final int removedCount = removedFromList.size();
23720                    for (int i = 0; i < removedCount; i++) {
23721                        deletePackageIfUnusedLPr(removedFromList.get(i));
23722                    }
23723                }
23724            }
23725        }
23726
23727        @Override
23728        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23729            synchronized (mPackages) {
23730                return mPermissionManager.isPermissionsReviewRequired(
23731                        mPackages.get(packageName), userId);
23732            }
23733        }
23734
23735        @Override
23736        public PackageInfo getPackageInfo(
23737                String packageName, int flags, int filterCallingUid, int userId) {
23738            return PackageManagerService.this
23739                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
23740                            flags, filterCallingUid, userId);
23741        }
23742
23743        @Override
23744        public int getPackageUid(String packageName, int flags, int userId) {
23745            return PackageManagerService.this
23746                    .getPackageUid(packageName, flags, userId);
23747        }
23748
23749        @Override
23750        public ApplicationInfo getApplicationInfo(
23751                String packageName, int flags, int filterCallingUid, int userId) {
23752            return PackageManagerService.this
23753                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
23754        }
23755
23756        @Override
23757        public ActivityInfo getActivityInfo(
23758                ComponentName component, int flags, int filterCallingUid, int userId) {
23759            return PackageManagerService.this
23760                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
23761        }
23762
23763        @Override
23764        public List<ResolveInfo> queryIntentActivities(
23765                Intent intent, int flags, int filterCallingUid, int userId) {
23766            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23767            return PackageManagerService.this
23768                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
23769                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
23770        }
23771
23772        @Override
23773        public List<ResolveInfo> queryIntentServices(
23774                Intent intent, int flags, int callingUid, int userId) {
23775            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23776            return PackageManagerService.this
23777                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
23778                            false);
23779        }
23780
23781        @Override
23782        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23783                int userId) {
23784            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23785        }
23786
23787        @Override
23788        public ComponentName getDefaultHomeActivity(int userId) {
23789            return PackageManagerService.this.getDefaultHomeActivity(userId);
23790        }
23791
23792        @Override
23793        public void setDeviceAndProfileOwnerPackages(
23794                int deviceOwnerUserId, String deviceOwnerPackage,
23795                SparseArray<String> profileOwnerPackages) {
23796            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23797                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23798        }
23799
23800        @Override
23801        public boolean isPackageDataProtected(int userId, String packageName) {
23802            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23803        }
23804
23805        @Override
23806        public boolean isPackageEphemeral(int userId, String packageName) {
23807            synchronized (mPackages) {
23808                final PackageSetting ps = mSettings.mPackages.get(packageName);
23809                return ps != null ? ps.getInstantApp(userId) : false;
23810            }
23811        }
23812
23813        @Override
23814        public boolean wasPackageEverLaunched(String packageName, int userId) {
23815            synchronized (mPackages) {
23816                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23817            }
23818        }
23819
23820        @Override
23821        public void grantRuntimePermission(String packageName, String permName, int userId,
23822                boolean overridePolicy) {
23823            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
23824                    permName, packageName, overridePolicy, getCallingUid(), userId,
23825                    mPermissionCallback);
23826        }
23827
23828        @Override
23829        public void revokeRuntimePermission(String packageName, String permName, int userId,
23830                boolean overridePolicy) {
23831            mPermissionManager.revokeRuntimePermission(
23832                    permName, packageName, overridePolicy, getCallingUid(), userId,
23833                    mPermissionCallback);
23834        }
23835
23836        @Override
23837        public String getNameForUid(int uid) {
23838            return PackageManagerService.this.getNameForUid(uid);
23839        }
23840
23841        @Override
23842        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23843                Intent origIntent, String resolvedType, String callingPackage,
23844                Bundle verificationBundle, int userId) {
23845            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23846                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
23847                    userId);
23848        }
23849
23850        @Override
23851        public void grantEphemeralAccess(int userId, Intent intent,
23852                int targetAppId, int ephemeralAppId) {
23853            synchronized (mPackages) {
23854                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23855                        targetAppId, ephemeralAppId);
23856            }
23857        }
23858
23859        @Override
23860        public boolean isInstantAppInstallerComponent(ComponentName component) {
23861            synchronized (mPackages) {
23862                return mInstantAppInstallerActivity != null
23863                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23864            }
23865        }
23866
23867        @Override
23868        public void pruneInstantApps() {
23869            mInstantAppRegistry.pruneInstantApps();
23870        }
23871
23872        @Override
23873        public String getSetupWizardPackageName() {
23874            return mSetupWizardPackage;
23875        }
23876
23877        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23878            if (policy != null) {
23879                mExternalSourcesPolicy = policy;
23880            }
23881        }
23882
23883        @Override
23884        public boolean isPackagePersistent(String packageName) {
23885            synchronized (mPackages) {
23886                PackageParser.Package pkg = mPackages.get(packageName);
23887                return pkg != null
23888                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23889                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23890                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23891                        : false;
23892            }
23893        }
23894
23895        @Override
23896        public boolean isLegacySystemApp(Package pkg) {
23897            synchronized (mPackages) {
23898                final PackageSetting ps = (PackageSetting) pkg.mExtras;
23899                return mPromoteSystemApps
23900                        && ps.isSystem()
23901                        && mExistingSystemPackages.contains(ps.name);
23902            }
23903        }
23904
23905        @Override
23906        public List<PackageInfo> getOverlayPackages(int userId) {
23907            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23908            synchronized (mPackages) {
23909                for (PackageParser.Package p : mPackages.values()) {
23910                    if (p.mOverlayTarget != null) {
23911                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23912                        if (pkg != null) {
23913                            overlayPackages.add(pkg);
23914                        }
23915                    }
23916                }
23917            }
23918            return overlayPackages;
23919        }
23920
23921        @Override
23922        public List<String> getTargetPackageNames(int userId) {
23923            List<String> targetPackages = new ArrayList<>();
23924            synchronized (mPackages) {
23925                for (PackageParser.Package p : mPackages.values()) {
23926                    if (p.mOverlayTarget == null) {
23927                        targetPackages.add(p.packageName);
23928                    }
23929                }
23930            }
23931            return targetPackages;
23932        }
23933
23934        @Override
23935        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23936                @Nullable List<String> overlayPackageNames) {
23937            synchronized (mPackages) {
23938                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23939                    Slog.e(TAG, "failed to find package " + targetPackageName);
23940                    return false;
23941                }
23942                ArrayList<String> overlayPaths = null;
23943                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
23944                    final int N = overlayPackageNames.size();
23945                    overlayPaths = new ArrayList<>(N);
23946                    for (int i = 0; i < N; i++) {
23947                        final String packageName = overlayPackageNames.get(i);
23948                        final PackageParser.Package pkg = mPackages.get(packageName);
23949                        if (pkg == null) {
23950                            Slog.e(TAG, "failed to find package " + packageName);
23951                            return false;
23952                        }
23953                        overlayPaths.add(pkg.baseCodePath);
23954                    }
23955                }
23956
23957                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
23958                ps.setOverlayPaths(overlayPaths, userId);
23959                return true;
23960            }
23961        }
23962
23963        @Override
23964        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23965                int flags, int userId, boolean resolveForStart) {
23966            return resolveIntentInternal(
23967                    intent, resolvedType, flags, userId, resolveForStart);
23968        }
23969
23970        @Override
23971        public ResolveInfo resolveService(Intent intent, String resolvedType,
23972                int flags, int userId, int callingUid) {
23973            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
23974        }
23975
23976        @Override
23977        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
23978            return PackageManagerService.this.resolveContentProviderInternal(
23979                    name, flags, userId);
23980        }
23981
23982        @Override
23983        public void addIsolatedUid(int isolatedUid, int ownerUid) {
23984            synchronized (mPackages) {
23985                mIsolatedOwners.put(isolatedUid, ownerUid);
23986            }
23987        }
23988
23989        @Override
23990        public void removeIsolatedUid(int isolatedUid) {
23991            synchronized (mPackages) {
23992                mIsolatedOwners.delete(isolatedUid);
23993            }
23994        }
23995
23996        @Override
23997        public int getUidTargetSdkVersion(int uid) {
23998            synchronized (mPackages) {
23999                return getUidTargetSdkVersionLockedLPr(uid);
24000            }
24001        }
24002
24003        @Override
24004        public int getPackageTargetSdkVersion(String packageName) {
24005            synchronized (mPackages) {
24006                return getPackageTargetSdkVersionLockedLPr(packageName);
24007            }
24008        }
24009
24010        @Override
24011        public boolean canAccessInstantApps(int callingUid, int userId) {
24012            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24013        }
24014
24015        @Override
24016        public boolean canAccessComponent(int callingUid, ComponentName component, int userId) {
24017            synchronized (mPackages) {
24018                final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
24019                return !PackageManagerService.this.filterAppAccessLPr(
24020                        ps, callingUid, component, TYPE_UNKNOWN, userId);
24021            }
24022        }
24023
24024        @Override
24025        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
24026            synchronized (mPackages) {
24027                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
24028            }
24029        }
24030
24031        @Override
24032        public void notifyPackageUse(String packageName, int reason) {
24033            synchronized (mPackages) {
24034                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
24035            }
24036        }
24037    }
24038
24039    @Override
24040    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24041        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24042        synchronized (mPackages) {
24043            final long identity = Binder.clearCallingIdentity();
24044            try {
24045                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
24046                        packageNames, userId);
24047            } finally {
24048                Binder.restoreCallingIdentity(identity);
24049            }
24050        }
24051    }
24052
24053    @Override
24054    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24055        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24056        synchronized (mPackages) {
24057            final long identity = Binder.clearCallingIdentity();
24058            try {
24059                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
24060                        packageNames, userId);
24061            } finally {
24062                Binder.restoreCallingIdentity(identity);
24063            }
24064        }
24065    }
24066
24067    private static void enforceSystemOrPhoneCaller(String tag) {
24068        int callingUid = Binder.getCallingUid();
24069        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24070            throw new SecurityException(
24071                    "Cannot call " + tag + " from UID " + callingUid);
24072        }
24073    }
24074
24075    boolean isHistoricalPackageUsageAvailable() {
24076        return mPackageUsage.isHistoricalPackageUsageAvailable();
24077    }
24078
24079    /**
24080     * Return a <b>copy</b> of the collection of packages known to the package manager.
24081     * @return A copy of the values of mPackages.
24082     */
24083    Collection<PackageParser.Package> getPackages() {
24084        synchronized (mPackages) {
24085            return new ArrayList<>(mPackages.values());
24086        }
24087    }
24088
24089    /**
24090     * Logs process start information (including base APK hash) to the security log.
24091     * @hide
24092     */
24093    @Override
24094    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24095            String apkFile, int pid) {
24096        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24097            return;
24098        }
24099        if (!SecurityLog.isLoggingEnabled()) {
24100            return;
24101        }
24102        Bundle data = new Bundle();
24103        data.putLong("startTimestamp", System.currentTimeMillis());
24104        data.putString("processName", processName);
24105        data.putInt("uid", uid);
24106        data.putString("seinfo", seinfo);
24107        data.putString("apkFile", apkFile);
24108        data.putInt("pid", pid);
24109        Message msg = mProcessLoggingHandler.obtainMessage(
24110                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24111        msg.setData(data);
24112        mProcessLoggingHandler.sendMessage(msg);
24113    }
24114
24115    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24116        return mCompilerStats.getPackageStats(pkgName);
24117    }
24118
24119    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24120        return getOrCreateCompilerPackageStats(pkg.packageName);
24121    }
24122
24123    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24124        return mCompilerStats.getOrCreatePackageStats(pkgName);
24125    }
24126
24127    public void deleteCompilerPackageStats(String pkgName) {
24128        mCompilerStats.deletePackageStats(pkgName);
24129    }
24130
24131    @Override
24132    public int getInstallReason(String packageName, int userId) {
24133        final int callingUid = Binder.getCallingUid();
24134        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24135                true /* requireFullPermission */, false /* checkShell */,
24136                "get install reason");
24137        synchronized (mPackages) {
24138            final PackageSetting ps = mSettings.mPackages.get(packageName);
24139            if (filterAppAccessLPr(ps, callingUid, userId)) {
24140                return PackageManager.INSTALL_REASON_UNKNOWN;
24141            }
24142            if (ps != null) {
24143                return ps.getInstallReason(userId);
24144            }
24145        }
24146        return PackageManager.INSTALL_REASON_UNKNOWN;
24147    }
24148
24149    @Override
24150    public boolean canRequestPackageInstalls(String packageName, int userId) {
24151        return canRequestPackageInstallsInternal(packageName, 0, userId,
24152                true /* throwIfPermNotDeclared*/);
24153    }
24154
24155    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24156            boolean throwIfPermNotDeclared) {
24157        int callingUid = Binder.getCallingUid();
24158        int uid = getPackageUid(packageName, 0, userId);
24159        if (callingUid != uid && callingUid != Process.ROOT_UID
24160                && callingUid != Process.SYSTEM_UID) {
24161            throw new SecurityException(
24162                    "Caller uid " + callingUid + " does not own package " + packageName);
24163        }
24164        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24165        if (info == null) {
24166            return false;
24167        }
24168        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24169            return false;
24170        }
24171        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24172        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24173        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24174            if (throwIfPermNotDeclared) {
24175                throw new SecurityException("Need to declare " + appOpPermission
24176                        + " to call this api");
24177            } else {
24178                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24179                return false;
24180            }
24181        }
24182        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24183            return false;
24184        }
24185        if (mExternalSourcesPolicy != null) {
24186            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24187            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24188                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24189            }
24190        }
24191        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24192    }
24193
24194    @Override
24195    public ComponentName getInstantAppResolverSettingsComponent() {
24196        return mInstantAppResolverSettingsComponent;
24197    }
24198
24199    @Override
24200    public ComponentName getInstantAppInstallerComponent() {
24201        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24202            return null;
24203        }
24204        return mInstantAppInstallerActivity == null
24205                ? null : mInstantAppInstallerActivity.getComponentName();
24206    }
24207
24208    @Override
24209    public String getInstantAppAndroidId(String packageName, int userId) {
24210        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24211                "getInstantAppAndroidId");
24212        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
24213                true /* requireFullPermission */, false /* checkShell */,
24214                "getInstantAppAndroidId");
24215        // Make sure the target is an Instant App.
24216        if (!isInstantApp(packageName, userId)) {
24217            return null;
24218        }
24219        synchronized (mPackages) {
24220            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24221        }
24222    }
24223
24224    boolean canHaveOatDir(String packageName) {
24225        synchronized (mPackages) {
24226            PackageParser.Package p = mPackages.get(packageName);
24227            if (p == null) {
24228                return false;
24229            }
24230            return p.canHaveOatDir();
24231        }
24232    }
24233
24234    private String getOatDir(PackageParser.Package pkg) {
24235        if (!pkg.canHaveOatDir()) {
24236            return null;
24237        }
24238        File codePath = new File(pkg.codePath);
24239        if (codePath.isDirectory()) {
24240            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
24241        }
24242        return null;
24243    }
24244
24245    void deleteOatArtifactsOfPackage(String packageName) {
24246        final String[] instructionSets;
24247        final List<String> codePaths;
24248        final String oatDir;
24249        final PackageParser.Package pkg;
24250        synchronized (mPackages) {
24251            pkg = mPackages.get(packageName);
24252        }
24253        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
24254        codePaths = pkg.getAllCodePaths();
24255        oatDir = getOatDir(pkg);
24256
24257        for (String codePath : codePaths) {
24258            for (String isa : instructionSets) {
24259                try {
24260                    mInstaller.deleteOdex(codePath, isa, oatDir);
24261                } catch (InstallerException e) {
24262                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
24263                }
24264            }
24265        }
24266    }
24267
24268    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
24269        Set<String> unusedPackages = new HashSet<>();
24270        long currentTimeInMillis = System.currentTimeMillis();
24271        synchronized (mPackages) {
24272            for (PackageParser.Package pkg : mPackages.values()) {
24273                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
24274                if (ps == null) {
24275                    continue;
24276                }
24277                PackageDexUsage.PackageUseInfo packageUseInfo =
24278                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
24279                if (PackageManagerServiceUtils
24280                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
24281                                downgradeTimeThresholdMillis, packageUseInfo,
24282                                pkg.getLatestPackageUseTimeInMills(),
24283                                pkg.getLatestForegroundPackageUseTimeInMills())) {
24284                    unusedPackages.add(pkg.packageName);
24285                }
24286            }
24287        }
24288        return unusedPackages;
24289    }
24290
24291    @Override
24292    public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning,
24293            int userId) {
24294        final int callingUid = Binder.getCallingUid();
24295        final int callingAppId = UserHandle.getAppId(callingUid);
24296
24297        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24298                true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo");
24299
24300        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24301                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24302            throw new SecurityException("Caller must have the "
24303                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24304        }
24305
24306        synchronized(mPackages) {
24307            mSettings.setHarmfulAppWarningLPw(packageName, warning, userId);
24308            scheduleWritePackageRestrictionsLocked(userId);
24309        }
24310    }
24311
24312    @Nullable
24313    @Override
24314    public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) {
24315        final int callingUid = Binder.getCallingUid();
24316        final int callingAppId = UserHandle.getAppId(callingUid);
24317
24318        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24319                true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo");
24320
24321        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24322                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24323            throw new SecurityException("Caller must have the "
24324                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24325        }
24326
24327        synchronized(mPackages) {
24328            return mSettings.getHarmfulAppWarningLPr(packageName, userId);
24329        }
24330    }
24331}
24332
24333interface PackageSender {
24334    /**
24335     * @param userIds User IDs where the action occurred on a full application
24336     * @param instantUserIds User IDs where the action occurred on an instant application
24337     */
24338    void sendPackageBroadcast(final String action, final String pkg,
24339        final Bundle extras, final int flags, final String targetPkg,
24340        final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds);
24341    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
24342        boolean includeStopped, int appId, int[] userIds, int[] instantUserIds);
24343    void notifyPackageAdded(String packageName);
24344    void notifyPackageRemoved(String packageName);
24345}
24346