PackageManagerService.java revision 1e0c91968e802d49c26e2e8d6ca6e8d31f451894
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.SET_HARMFUL_APP_WARNINGS;
21import static android.Manifest.permission.INSTALL_PACKAGES;
22import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS;
23import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
24import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
25import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
26import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
27import static android.content.pm.PackageManager.CERT_INPUT_RAW_X509;
28import static android.content.pm.PackageManager.CERT_INPUT_SHA256;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
31import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
32import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
33import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
34import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
39import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
40import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
41import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
42import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
43import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
44import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
45import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
49import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
50import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
51import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
52import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
53import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
54import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
55import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
56import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
57import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
58import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
59import static android.content.pm.PackageManager.INSTALL_INTERNAL;
60import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
66import static android.content.pm.PackageManager.MATCH_ALL;
67import static android.content.pm.PackageManager.MATCH_ANY_USER;
68import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
71import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
72import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
73import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
74import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
75import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
76import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
77import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
78import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
79import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
80import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER;
81import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
82import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
83import static android.content.pm.PackageManager.PERMISSION_DENIED;
84import static android.content.pm.PackageManager.PERMISSION_GRANTED;
85import static android.content.pm.PackageParser.isApkFile;
86import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
87import static android.os.storage.StorageManager.FLAG_STORAGE_CE;
88import static android.os.storage.StorageManager.FLAG_STORAGE_DE;
89import static android.system.OsConstants.O_CREAT;
90import static android.system.OsConstants.O_RDWR;
91import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
92import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
93import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
94import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
95import static com.android.internal.util.ArrayUtils.appendInt;
96import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
97import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
98import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
99import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
100import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
102import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
103import static com.android.server.pm.PackageManagerServiceUtils.compareSignatures;
104import static com.android.server.pm.PackageManagerServiceUtils.compressedFileExists;
105import static com.android.server.pm.PackageManagerServiceUtils.decompressFile;
106import static com.android.server.pm.PackageManagerServiceUtils.deriveAbiOverride;
107import static com.android.server.pm.PackageManagerServiceUtils.dumpCriticalInfo;
108import static com.android.server.pm.PackageManagerServiceUtils.getCompressedFiles;
109import static com.android.server.pm.PackageManagerServiceUtils.getLastModifiedTime;
110import static com.android.server.pm.PackageManagerServiceUtils.logCriticalInfo;
111import static com.android.server.pm.PackageManagerServiceUtils.signingDetailsHasCertificate;
112import static com.android.server.pm.PackageManagerServiceUtils.signingDetailsHasSha256Certificate;
113import static com.android.server.pm.PackageManagerServiceUtils.verifySignatures;
114import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_FAILURE;
115import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS;
116import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
117
118import android.Manifest;
119import android.annotation.IntDef;
120import android.annotation.NonNull;
121import android.annotation.Nullable;
122import android.app.ActivityManager;
123import android.app.ActivityManagerInternal;
124import android.app.AppOpsManager;
125import android.app.IActivityManager;
126import android.app.ResourcesManager;
127import android.app.admin.IDevicePolicyManager;
128import android.app.admin.SecurityLog;
129import android.app.backup.IBackupManager;
130import android.content.BroadcastReceiver;
131import android.content.ComponentName;
132import android.content.ContentResolver;
133import android.content.Context;
134import android.content.IIntentReceiver;
135import android.content.Intent;
136import android.content.IntentFilter;
137import android.content.IntentSender;
138import android.content.IntentSender.SendIntentException;
139import android.content.ServiceConnection;
140import android.content.pm.ActivityInfo;
141import android.content.pm.ApplicationInfo;
142import android.content.pm.AppsQueryHelper;
143import android.content.pm.AuxiliaryResolveInfo;
144import android.content.pm.ChangedPackages;
145import android.content.pm.ComponentInfo;
146import android.content.pm.FallbackCategoryProvider;
147import android.content.pm.FeatureInfo;
148import android.content.pm.IDexModuleRegisterCallback;
149import android.content.pm.IOnPermissionsChangeListener;
150import android.content.pm.IPackageDataObserver;
151import android.content.pm.IPackageDeleteObserver;
152import android.content.pm.IPackageDeleteObserver2;
153import android.content.pm.IPackageInstallObserver2;
154import android.content.pm.IPackageInstaller;
155import android.content.pm.IPackageManager;
156import android.content.pm.IPackageManagerNative;
157import android.content.pm.IPackageMoveObserver;
158import android.content.pm.IPackageStatsObserver;
159import android.content.pm.InstantAppInfo;
160import android.content.pm.InstantAppRequest;
161import android.content.pm.InstantAppResolveInfo;
162import android.content.pm.InstrumentationInfo;
163import android.content.pm.IntentFilterVerificationInfo;
164import android.content.pm.KeySet;
165import android.content.pm.PackageCleanItem;
166import android.content.pm.PackageInfo;
167import android.content.pm.PackageInfoLite;
168import android.content.pm.PackageInstaller;
169import android.content.pm.PackageList;
170import android.content.pm.PackageManager;
171import android.content.pm.PackageManagerInternal;
172import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
173import android.content.pm.PackageManagerInternal.PackageListObserver;
174import android.content.pm.PackageParser;
175import android.content.pm.PackageParser.ActivityIntentInfo;
176import android.content.pm.PackageParser.Package;
177import android.content.pm.PackageParser.PackageLite;
178import android.content.pm.PackageParser.PackageParserException;
179import android.content.pm.PackageParser.ParseFlags;
180import android.content.pm.PackageParser.ServiceIntentInfo;
181import android.content.pm.PackageParser.SigningDetails.SignatureSchemeVersion;
182import android.content.pm.PackageStats;
183import android.content.pm.PackageUserState;
184import android.content.pm.ParceledListSlice;
185import android.content.pm.PermissionGroupInfo;
186import android.content.pm.PermissionInfo;
187import android.content.pm.ProviderInfo;
188import android.content.pm.ResolveInfo;
189import android.content.pm.ServiceInfo;
190import android.content.pm.SharedLibraryInfo;
191import android.content.pm.Signature;
192import android.content.pm.UserInfo;
193import android.content.pm.VerifierDeviceIdentity;
194import android.content.pm.VerifierInfo;
195import android.content.pm.VersionedPackage;
196import android.content.pm.dex.ArtManager;
197import android.content.pm.dex.DexMetadataHelper;
198import android.content.pm.dex.IArtManager;
199import android.content.res.Resources;
200import android.database.ContentObserver;
201import android.graphics.Bitmap;
202import android.hardware.display.DisplayManager;
203import android.net.Uri;
204import android.os.Binder;
205import android.os.Build;
206import android.os.Bundle;
207import android.os.Debug;
208import android.os.Environment;
209import android.os.Environment.UserEnvironment;
210import android.os.FileUtils;
211import android.os.Handler;
212import android.os.IBinder;
213import android.os.Looper;
214import android.os.Message;
215import android.os.Parcel;
216import android.os.ParcelFileDescriptor;
217import android.os.PatternMatcher;
218import android.os.Process;
219import android.os.RemoteCallbackList;
220import android.os.RemoteException;
221import android.os.ResultReceiver;
222import android.os.SELinux;
223import android.os.ServiceManager;
224import android.os.ShellCallback;
225import android.os.SystemClock;
226import android.os.SystemProperties;
227import android.os.Trace;
228import android.os.UserHandle;
229import android.os.UserManager;
230import android.os.UserManagerInternal;
231import android.os.storage.IStorageManager;
232import android.os.storage.StorageEventListener;
233import android.os.storage.StorageManager;
234import android.os.storage.StorageManagerInternal;
235import android.os.storage.VolumeInfo;
236import android.os.storage.VolumeRecord;
237import android.provider.Settings.Global;
238import android.provider.Settings.Secure;
239import android.security.KeyStore;
240import android.security.SystemKeyStore;
241import android.service.pm.PackageServiceDumpProto;
242import android.system.ErrnoException;
243import android.system.Os;
244import android.text.TextUtils;
245import android.text.format.DateUtils;
246import android.util.ArrayMap;
247import android.util.ArraySet;
248import android.util.Base64;
249import android.util.DisplayMetrics;
250import android.util.EventLog;
251import android.util.ExceptionUtils;
252import android.util.Log;
253import android.util.LogPrinter;
254import android.util.LongSparseArray;
255import android.util.LongSparseLongArray;
256import android.util.MathUtils;
257import android.util.PackageUtils;
258import android.util.Pair;
259import android.util.PrintStreamPrinter;
260import android.util.Slog;
261import android.util.SparseArray;
262import android.util.SparseBooleanArray;
263import android.util.SparseIntArray;
264import android.util.TimingsTraceLog;
265import android.util.Xml;
266import android.util.jar.StrictJarFile;
267import android.util.proto.ProtoOutputStream;
268import android.view.Display;
269
270import com.android.internal.R;
271import com.android.internal.annotations.GuardedBy;
272import com.android.internal.app.IMediaContainerService;
273import com.android.internal.app.ResolverActivity;
274import com.android.internal.content.NativeLibraryHelper;
275import com.android.internal.content.PackageHelper;
276import com.android.internal.logging.MetricsLogger;
277import com.android.internal.os.IParcelFileDescriptorFactory;
278import com.android.internal.os.SomeArgs;
279import com.android.internal.os.Zygote;
280import com.android.internal.telephony.CarrierAppUtils;
281import com.android.internal.util.ArrayUtils;
282import com.android.internal.util.ConcurrentUtils;
283import com.android.internal.util.DumpUtils;
284import com.android.internal.util.FastXmlSerializer;
285import com.android.internal.util.IndentingPrintWriter;
286import com.android.internal.util.Preconditions;
287import com.android.internal.util.XmlUtils;
288import com.android.server.AttributeCache;
289import com.android.server.DeviceIdleController;
290import com.android.server.EventLogTags;
291import com.android.server.FgThread;
292import com.android.server.IntentResolver;
293import com.android.server.LocalServices;
294import com.android.server.LockGuard;
295import com.android.server.ServiceThread;
296import com.android.server.SystemConfig;
297import com.android.server.SystemServerInitThreadPool;
298import com.android.server.Watchdog;
299import com.android.server.net.NetworkPolicyManagerInternal;
300import com.android.server.pm.Installer.InstallerException;
301import com.android.server.pm.Settings.DatabaseVersion;
302import com.android.server.pm.Settings.VersionInfo;
303import com.android.server.pm.dex.ArtManagerService;
304import com.android.server.pm.dex.DexLogger;
305import com.android.server.pm.dex.DexManager;
306import com.android.server.pm.dex.DexoptOptions;
307import com.android.server.pm.dex.PackageDexUsage;
308import com.android.server.pm.permission.BasePermission;
309import com.android.server.pm.permission.DefaultPermissionGrantPolicy;
310import com.android.server.pm.permission.PermissionManagerService;
311import com.android.server.pm.permission.PermissionManagerInternal;
312import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback;
313import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback;
314import com.android.server.pm.permission.PermissionsState;
315import com.android.server.pm.permission.PermissionsState.PermissionState;
316import com.android.server.security.VerityUtils;
317import com.android.server.storage.DeviceStorageMonitorInternal;
318
319import dalvik.system.CloseGuard;
320import dalvik.system.VMRuntime;
321
322import libcore.io.IoUtils;
323
324import org.xmlpull.v1.XmlPullParser;
325import org.xmlpull.v1.XmlPullParserException;
326import org.xmlpull.v1.XmlSerializer;
327
328import java.io.BufferedOutputStream;
329import java.io.ByteArrayInputStream;
330import java.io.ByteArrayOutputStream;
331import java.io.File;
332import java.io.FileDescriptor;
333import java.io.FileInputStream;
334import java.io.FileOutputStream;
335import java.io.FilenameFilter;
336import java.io.IOException;
337import java.io.PrintWriter;
338import java.lang.annotation.Retention;
339import java.lang.annotation.RetentionPolicy;
340import java.nio.charset.StandardCharsets;
341import java.security.DigestException;
342import java.security.DigestInputStream;
343import java.security.MessageDigest;
344import java.security.NoSuchAlgorithmException;
345import java.security.PublicKey;
346import java.security.SecureRandom;
347import java.security.cert.CertificateException;
348import java.util.ArrayList;
349import java.util.Arrays;
350import java.util.Collection;
351import java.util.Collections;
352import java.util.Comparator;
353import java.util.HashMap;
354import java.util.HashSet;
355import java.util.Iterator;
356import java.util.LinkedHashSet;
357import java.util.List;
358import java.util.Map;
359import java.util.Objects;
360import java.util.Set;
361import java.util.concurrent.CountDownLatch;
362import java.util.concurrent.Future;
363import java.util.concurrent.TimeUnit;
364import java.util.concurrent.atomic.AtomicBoolean;
365import java.util.concurrent.atomic.AtomicInteger;
366
367/**
368 * Keep track of all those APKs everywhere.
369 * <p>
370 * Internally there are two important locks:
371 * <ul>
372 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
373 * and other related state. It is a fine-grained lock that should only be held
374 * momentarily, as it's one of the most contended locks in the system.
375 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
376 * operations typically involve heavy lifting of application data on disk. Since
377 * {@code installd} is single-threaded, and it's operations can often be slow,
378 * this lock should never be acquired while already holding {@link #mPackages}.
379 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
380 * holding {@link #mInstallLock}.
381 * </ul>
382 * Many internal methods rely on the caller to hold the appropriate locks, and
383 * this contract is expressed through method name suffixes:
384 * <ul>
385 * <li>fooLI(): the caller must hold {@link #mInstallLock}
386 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
387 * being modified must be frozen
388 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
389 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
390 * </ul>
391 * <p>
392 * Because this class is very central to the platform's security; please run all
393 * CTS and unit tests whenever making modifications:
394 *
395 * <pre>
396 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
397 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
398 * </pre>
399 */
400public class PackageManagerService extends IPackageManager.Stub
401        implements PackageSender {
402    static final String TAG = "PackageManager";
403    public static final boolean DEBUG_SETTINGS = false;
404    static final boolean DEBUG_PREFERRED = false;
405    static final boolean DEBUG_UPGRADE = false;
406    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
407    private static final boolean DEBUG_BACKUP = false;
408    public static final boolean DEBUG_INSTALL = false;
409    public static final boolean DEBUG_REMOVE = false;
410    private static final boolean DEBUG_BROADCASTS = false;
411    private static final boolean DEBUG_SHOW_INFO = false;
412    private static final boolean DEBUG_PACKAGE_INFO = false;
413    private static final boolean DEBUG_INTENT_MATCHING = false;
414    public static final boolean DEBUG_PACKAGE_SCANNING = false;
415    private static final boolean DEBUG_VERIFY = false;
416    private static final boolean DEBUG_FILTERS = false;
417    public static final boolean DEBUG_PERMISSIONS = false;
418    private static final boolean DEBUG_SHARED_LIBRARIES = false;
419    public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
420
421    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
422    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
423    // user, but by default initialize to this.
424    public static final boolean DEBUG_DEXOPT = false;
425
426    private static final boolean DEBUG_ABI_SELECTION = false;
427    private static final boolean DEBUG_EPHEMERAL = 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    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
558
559    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    }
587
588    /**
589     * The set of all protected actions [i.e. those actions for which a high priority
590     * intent filter is disallowed].
591     */
592    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
593    static {
594        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
595        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
596        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
597        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
598    }
599
600    // Compilation reasons.
601    public static final int REASON_FIRST_BOOT = 0;
602    public static final int REASON_BOOT = 1;
603    public static final int REASON_INSTALL = 2;
604    public static final int REASON_BACKGROUND_DEXOPT = 3;
605    public static final int REASON_AB_OTA = 4;
606    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
607    public static final int REASON_SHARED = 6;
608
609    public static final int REASON_LAST = REASON_SHARED;
610
611    /**
612     * Version number for the package parser cache. Increment this whenever the format or
613     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
614     */
615    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
616
617    /**
618     * Whether the package parser cache is enabled.
619     */
620    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
621
622    /**
623     * Permissions required in order to receive instant application lifecycle broadcasts.
624     */
625    private static final String[] INSTANT_APP_BROADCAST_PERMISSION =
626            new String[] { android.Manifest.permission.ACCESS_INSTANT_APPS };
627
628    final ServiceThread mHandlerThread;
629
630    final PackageHandler mHandler;
631
632    private final ProcessLoggingHandler mProcessLoggingHandler;
633
634    /**
635     * Messages for {@link #mHandler} that need to wait for system ready before
636     * being dispatched.
637     */
638    private ArrayList<Message> mPostSystemReadyMessages;
639
640    final int mSdkVersion = Build.VERSION.SDK_INT;
641
642    final Context mContext;
643    final boolean mFactoryTest;
644    final boolean mOnlyCore;
645    final DisplayMetrics mMetrics;
646    final int mDefParseFlags;
647    final String[] mSeparateProcesses;
648    final boolean mIsUpgrade;
649    final boolean mIsPreNUpgrade;
650    final boolean mIsPreNMR1Upgrade;
651
652    // Have we told the Activity Manager to whitelist the default container service by uid yet?
653    @GuardedBy("mPackages")
654    boolean mDefaultContainerWhitelisted = false;
655
656    @GuardedBy("mPackages")
657    private boolean mDexOptDialogShown;
658
659    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
660    // LOCK HELD.  Can be called with mInstallLock held.
661    @GuardedBy("mInstallLock")
662    final Installer mInstaller;
663
664    /** Directory where installed applications are stored */
665    private static final File sAppInstallDir =
666            new File(Environment.getDataDirectory(), "app");
667    /** Directory where installed application's 32-bit native libraries are copied. */
668    private static final File sAppLib32InstallDir =
669            new File(Environment.getDataDirectory(), "app-lib");
670    /** Directory where code and non-resource assets of forward-locked applications are stored */
671    private static final File sDrmAppPrivateInstallDir =
672            new File(Environment.getDataDirectory(), "app-private");
673
674    // ----------------------------------------------------------------
675
676    // Lock for state used when installing and doing other long running
677    // operations.  Methods that must be called with this lock held have
678    // the suffix "LI".
679    final Object mInstallLock = new Object();
680
681    // ----------------------------------------------------------------
682
683    // Keys are String (package name), values are Package.  This also serves
684    // as the lock for the global state.  Methods that must be called with
685    // this lock held have the prefix "LP".
686    @GuardedBy("mPackages")
687    final ArrayMap<String, PackageParser.Package> mPackages =
688            new ArrayMap<String, PackageParser.Package>();
689
690    final ArrayMap<String, Set<String>> mKnownCodebase =
691            new ArrayMap<String, Set<String>>();
692
693    // Keys are isolated uids and values are the uid of the application
694    // that created the isolated proccess.
695    @GuardedBy("mPackages")
696    final SparseIntArray mIsolatedOwners = new SparseIntArray();
697
698    /**
699     * Tracks new system packages [received in an OTA] that we expect to
700     * find updated user-installed versions. Keys are package name, values
701     * are package location.
702     */
703    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
704    /**
705     * Tracks high priority intent filters for protected actions. During boot, certain
706     * filter actions are protected and should never be allowed to have a high priority
707     * intent filter for them. However, there is one, and only one exception -- the
708     * setup wizard. It must be able to define a high priority intent filter for these
709     * actions to ensure there are no escapes from the wizard. We need to delay processing
710     * of these during boot as we need to look at all of the system packages in order
711     * to know which component is the setup wizard.
712     */
713    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
714    /**
715     * Whether or not processing protected filters should be deferred.
716     */
717    private boolean mDeferProtectedFilters = true;
718
719    /**
720     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
721     */
722    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
723    /**
724     * Whether or not system app permissions should be promoted from install to runtime.
725     */
726    boolean mPromoteSystemApps;
727
728    @GuardedBy("mPackages")
729    final Settings mSettings;
730
731    /**
732     * Set of package names that are currently "frozen", which means active
733     * surgery is being done on the code/data for that package. The platform
734     * will refuse to launch frozen packages to avoid race conditions.
735     *
736     * @see PackageFreezer
737     */
738    @GuardedBy("mPackages")
739    final ArraySet<String> mFrozenPackages = new ArraySet<>();
740
741    final ProtectedPackages mProtectedPackages;
742
743    @GuardedBy("mLoadedVolumes")
744    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
745
746    boolean mFirstBoot;
747
748    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
749
750    @GuardedBy("mAvailableFeatures")
751    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
752
753    private final InstantAppRegistry mInstantAppRegistry;
754
755    @GuardedBy("mPackages")
756    int mChangedPackagesSequenceNumber;
757    /**
758     * List of changed [installed, removed or updated] packages.
759     * mapping from user id -> sequence number -> package name
760     */
761    @GuardedBy("mPackages")
762    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
763    /**
764     * The sequence number of the last change to a package.
765     * mapping from user id -> package name -> sequence number
766     */
767    @GuardedBy("mPackages")
768    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
769
770    @GuardedBy("mPackages")
771    final private ArraySet<PackageListObserver> mPackageListObservers = new ArraySet<>();
772
773    class PackageParserCallback implements PackageParser.Callback {
774        @Override public final boolean hasFeature(String feature) {
775            return PackageManagerService.this.hasSystemFeature(feature, 0);
776        }
777
778        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
779                Collection<PackageParser.Package> allPackages, String targetPackageName) {
780            List<PackageParser.Package> overlayPackages = null;
781            for (PackageParser.Package p : allPackages) {
782                if (targetPackageName.equals(p.mOverlayTarget) && p.mOverlayIsStatic) {
783                    if (overlayPackages == null) {
784                        overlayPackages = new ArrayList<PackageParser.Package>();
785                    }
786                    overlayPackages.add(p);
787                }
788            }
789            if (overlayPackages != null) {
790                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
791                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
792                        return p1.mOverlayPriority - p2.mOverlayPriority;
793                    }
794                };
795                Collections.sort(overlayPackages, cmp);
796            }
797            return overlayPackages;
798        }
799
800        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
801                String targetPackageName, String targetPath) {
802            if ("android".equals(targetPackageName)) {
803                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
804                // native AssetManager.
805                return null;
806            }
807            List<PackageParser.Package> overlayPackages =
808                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
809            if (overlayPackages == null || overlayPackages.isEmpty()) {
810                return null;
811            }
812            List<String> overlayPathList = null;
813            for (PackageParser.Package overlayPackage : overlayPackages) {
814                if (targetPath == null) {
815                    if (overlayPathList == null) {
816                        overlayPathList = new ArrayList<String>();
817                    }
818                    overlayPathList.add(overlayPackage.baseCodePath);
819                    continue;
820                }
821
822                try {
823                    // Creates idmaps for system to parse correctly the Android manifest of the
824                    // target package.
825                    //
826                    // OverlayManagerService will update each of them with a correct gid from its
827                    // target package app id.
828                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
829                            UserHandle.getSharedAppGid(
830                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
831                    if (overlayPathList == null) {
832                        overlayPathList = new ArrayList<String>();
833                    }
834                    overlayPathList.add(overlayPackage.baseCodePath);
835                } catch (InstallerException e) {
836                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
837                            overlayPackage.baseCodePath);
838                }
839            }
840            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
841        }
842
843        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
844            synchronized (mPackages) {
845                return getStaticOverlayPathsLocked(
846                        mPackages.values(), targetPackageName, targetPath);
847            }
848        }
849
850        @Override public final String[] getOverlayApks(String targetPackageName) {
851            return getStaticOverlayPaths(targetPackageName, null);
852        }
853
854        @Override public final String[] getOverlayPaths(String targetPackageName,
855                String targetPath) {
856            return getStaticOverlayPaths(targetPackageName, targetPath);
857        }
858    }
859
860    class ParallelPackageParserCallback extends PackageParserCallback {
861        List<PackageParser.Package> mOverlayPackages = null;
862
863        void findStaticOverlayPackages() {
864            synchronized (mPackages) {
865                for (PackageParser.Package p : mPackages.values()) {
866                    if (p.mOverlayIsStatic) {
867                        if (mOverlayPackages == null) {
868                            mOverlayPackages = new ArrayList<PackageParser.Package>();
869                        }
870                        mOverlayPackages.add(p);
871                    }
872                }
873            }
874        }
875
876        @Override
877        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
878            // We can trust mOverlayPackages without holding mPackages because package uninstall
879            // can't happen while running parallel parsing.
880            // Moreover holding mPackages on each parsing thread causes dead-lock.
881            return mOverlayPackages == null ? null :
882                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
883        }
884    }
885
886    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
887    final ParallelPackageParserCallback mParallelPackageParserCallback =
888            new ParallelPackageParserCallback();
889
890    public static final class SharedLibraryEntry {
891        public final @Nullable String path;
892        public final @Nullable String apk;
893        public final @NonNull SharedLibraryInfo info;
894
895        SharedLibraryEntry(String _path, String _apk, String name, long version, int type,
896                String declaringPackageName, long declaringPackageVersionCode) {
897            path = _path;
898            apk = _apk;
899            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
900                    declaringPackageName, declaringPackageVersionCode), null);
901        }
902    }
903
904    // Currently known shared libraries.
905    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
906    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
907            new ArrayMap<>();
908
909    // All available activities, for your resolving pleasure.
910    final ActivityIntentResolver mActivities =
911            new ActivityIntentResolver();
912
913    // All available receivers, for your resolving pleasure.
914    final ActivityIntentResolver mReceivers =
915            new ActivityIntentResolver();
916
917    // All available services, for your resolving pleasure.
918    final ServiceIntentResolver mServices = new ServiceIntentResolver();
919
920    // All available providers, for your resolving pleasure.
921    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
922
923    // Mapping from provider base names (first directory in content URI codePath)
924    // to the provider information.
925    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
926            new ArrayMap<String, PackageParser.Provider>();
927
928    // Mapping from instrumentation class names to info about them.
929    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
930            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
931
932    // Packages whose data we have transfered into another package, thus
933    // should no longer exist.
934    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
935
936    // Broadcast actions that are only available to the system.
937    @GuardedBy("mProtectedBroadcasts")
938    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
939
940    /** List of packages waiting for verification. */
941    final SparseArray<PackageVerificationState> mPendingVerification
942            = new SparseArray<PackageVerificationState>();
943
944    final PackageInstallerService mInstallerService;
945
946    final ArtManagerService mArtManagerService;
947
948    private final PackageDexOptimizer mPackageDexOptimizer;
949    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
950    // is used by other apps).
951    private final DexManager mDexManager;
952
953    private AtomicInteger mNextMoveId = new AtomicInteger();
954    private final MoveCallbacks mMoveCallbacks;
955
956    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
957
958    // Cache of users who need badging.
959    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
960
961    /** Token for keys in mPendingVerification. */
962    private int mPendingVerificationToken = 0;
963
964    volatile boolean mSystemReady;
965    volatile boolean mSafeMode;
966    volatile boolean mHasSystemUidErrors;
967    private volatile boolean mEphemeralAppsDisabled;
968
969    ApplicationInfo mAndroidApplication;
970    final ActivityInfo mResolveActivity = new ActivityInfo();
971    final ResolveInfo mResolveInfo = new ResolveInfo();
972    ComponentName mResolveComponentName;
973    PackageParser.Package mPlatformPackage;
974    ComponentName mCustomResolverComponentName;
975
976    boolean mResolverReplaced = false;
977
978    private final @Nullable ComponentName mIntentFilterVerifierComponent;
979    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
980
981    private int mIntentFilterVerificationToken = 0;
982
983    /** The service connection to the ephemeral resolver */
984    final EphemeralResolverConnection mInstantAppResolverConnection;
985    /** Component used to show resolver settings for Instant Apps */
986    final ComponentName mInstantAppResolverSettingsComponent;
987
988    /** Activity used to install instant applications */
989    ActivityInfo mInstantAppInstallerActivity;
990    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
991
992    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
993            = new SparseArray<IntentFilterVerificationState>();
994
995    // TODO remove this and go through mPermissonManager directly
996    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
997    private final PermissionManagerInternal mPermissionManager;
998
999    // List of packages names to keep cached, even if they are uninstalled for all users
1000    private List<String> mKeepUninstalledPackages;
1001
1002    private UserManagerInternal mUserManagerInternal;
1003    private ActivityManagerInternal mActivityManagerInternal;
1004
1005    private DeviceIdleController.LocalService mDeviceIdleController;
1006
1007    private File mCacheDir;
1008
1009    private Future<?> mPrepareAppDataFuture;
1010
1011    private static class IFVerificationParams {
1012        PackageParser.Package pkg;
1013        boolean replacing;
1014        int userId;
1015        int verifierUid;
1016
1017        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1018                int _userId, int _verifierUid) {
1019            pkg = _pkg;
1020            replacing = _replacing;
1021            userId = _userId;
1022            replacing = _replacing;
1023            verifierUid = _verifierUid;
1024        }
1025    }
1026
1027    private interface IntentFilterVerifier<T extends IntentFilter> {
1028        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1029                                               T filter, String packageName);
1030        void startVerifications(int userId);
1031        void receiveVerificationResponse(int verificationId);
1032    }
1033
1034    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1035        private Context mContext;
1036        private ComponentName mIntentFilterVerifierComponent;
1037        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1038
1039        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1040            mContext = context;
1041            mIntentFilterVerifierComponent = verifierComponent;
1042        }
1043
1044        private String getDefaultScheme() {
1045            return IntentFilter.SCHEME_HTTPS;
1046        }
1047
1048        @Override
1049        public void startVerifications(int userId) {
1050            // Launch verifications requests
1051            int count = mCurrentIntentFilterVerifications.size();
1052            for (int n=0; n<count; n++) {
1053                int verificationId = mCurrentIntentFilterVerifications.get(n);
1054                final IntentFilterVerificationState ivs =
1055                        mIntentFilterVerificationStates.get(verificationId);
1056
1057                String packageName = ivs.getPackageName();
1058
1059                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1060                final int filterCount = filters.size();
1061                ArraySet<String> domainsSet = new ArraySet<>();
1062                for (int m=0; m<filterCount; m++) {
1063                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1064                    domainsSet.addAll(filter.getHostsList());
1065                }
1066                synchronized (mPackages) {
1067                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1068                            packageName, domainsSet) != null) {
1069                        scheduleWriteSettingsLocked();
1070                    }
1071                }
1072                sendVerificationRequest(verificationId, ivs);
1073            }
1074            mCurrentIntentFilterVerifications.clear();
1075        }
1076
1077        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1078            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1079            verificationIntent.putExtra(
1080                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1081                    verificationId);
1082            verificationIntent.putExtra(
1083                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1084                    getDefaultScheme());
1085            verificationIntent.putExtra(
1086                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1087                    ivs.getHostsString());
1088            verificationIntent.putExtra(
1089                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1090                    ivs.getPackageName());
1091            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1092            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1093
1094            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1095            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1096                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1097                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1098
1099            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1100            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1101                    "Sending IntentFilter verification broadcast");
1102        }
1103
1104        public void receiveVerificationResponse(int verificationId) {
1105            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1106
1107            final boolean verified = ivs.isVerified();
1108
1109            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1110            final int count = filters.size();
1111            if (DEBUG_DOMAIN_VERIFICATION) {
1112                Slog.i(TAG, "Received verification response " + verificationId
1113                        + " for " + count + " filters, verified=" + verified);
1114            }
1115            for (int n=0; n<count; n++) {
1116                PackageParser.ActivityIntentInfo filter = filters.get(n);
1117                filter.setVerified(verified);
1118
1119                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1120                        + " verified with result:" + verified + " and hosts:"
1121                        + ivs.getHostsString());
1122            }
1123
1124            mIntentFilterVerificationStates.remove(verificationId);
1125
1126            final String packageName = ivs.getPackageName();
1127            IntentFilterVerificationInfo ivi = null;
1128
1129            synchronized (mPackages) {
1130                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1131            }
1132            if (ivi == null) {
1133                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1134                        + verificationId + " packageName:" + packageName);
1135                return;
1136            }
1137            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1138                    "Updating IntentFilterVerificationInfo for package " + packageName
1139                            +" verificationId:" + verificationId);
1140
1141            synchronized (mPackages) {
1142                if (verified) {
1143                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1144                } else {
1145                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1146                }
1147                scheduleWriteSettingsLocked();
1148
1149                final int userId = ivs.getUserId();
1150                if (userId != UserHandle.USER_ALL) {
1151                    final int userStatus =
1152                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1153
1154                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1155                    boolean needUpdate = false;
1156
1157                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1158                    // already been set by the User thru the Disambiguation dialog
1159                    switch (userStatus) {
1160                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1161                            if (verified) {
1162                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1163                            } else {
1164                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1165                            }
1166                            needUpdate = true;
1167                            break;
1168
1169                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1170                            if (verified) {
1171                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1172                                needUpdate = true;
1173                            }
1174                            break;
1175
1176                        default:
1177                            // Nothing to do
1178                    }
1179
1180                    if (needUpdate) {
1181                        mSettings.updateIntentFilterVerificationStatusLPw(
1182                                packageName, updatedStatus, userId);
1183                        scheduleWritePackageRestrictionsLocked(userId);
1184                    }
1185                }
1186            }
1187        }
1188
1189        @Override
1190        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1191                    ActivityIntentInfo filter, String packageName) {
1192            if (!hasValidDomains(filter)) {
1193                return false;
1194            }
1195            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1196            if (ivs == null) {
1197                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1198                        packageName);
1199            }
1200            if (DEBUG_DOMAIN_VERIFICATION) {
1201                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1202            }
1203            ivs.addFilter(filter);
1204            return true;
1205        }
1206
1207        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1208                int userId, int verificationId, String packageName) {
1209            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1210                    verifierUid, userId, packageName);
1211            ivs.setPendingState();
1212            synchronized (mPackages) {
1213                mIntentFilterVerificationStates.append(verificationId, ivs);
1214                mCurrentIntentFilterVerifications.add(verificationId);
1215            }
1216            return ivs;
1217        }
1218    }
1219
1220    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1221        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1222                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1223                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1224    }
1225
1226    // Set of pending broadcasts for aggregating enable/disable of components.
1227    static class PendingPackageBroadcasts {
1228        // for each user id, a map of <package name -> components within that package>
1229        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1230
1231        public PendingPackageBroadcasts() {
1232            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1233        }
1234
1235        public ArrayList<String> get(int userId, String packageName) {
1236            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1237            return packages.get(packageName);
1238        }
1239
1240        public void put(int userId, String packageName, ArrayList<String> components) {
1241            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1242            packages.put(packageName, components);
1243        }
1244
1245        public void remove(int userId, String packageName) {
1246            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1247            if (packages != null) {
1248                packages.remove(packageName);
1249            }
1250        }
1251
1252        public void remove(int userId) {
1253            mUidMap.remove(userId);
1254        }
1255
1256        public int userIdCount() {
1257            return mUidMap.size();
1258        }
1259
1260        public int userIdAt(int n) {
1261            return mUidMap.keyAt(n);
1262        }
1263
1264        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1265            return mUidMap.get(userId);
1266        }
1267
1268        public int size() {
1269            // total number of pending broadcast entries across all userIds
1270            int num = 0;
1271            for (int i = 0; i< mUidMap.size(); i++) {
1272                num += mUidMap.valueAt(i).size();
1273            }
1274            return num;
1275        }
1276
1277        public void clear() {
1278            mUidMap.clear();
1279        }
1280
1281        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1282            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1283            if (map == null) {
1284                map = new ArrayMap<String, ArrayList<String>>();
1285                mUidMap.put(userId, map);
1286            }
1287            return map;
1288        }
1289    }
1290    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1291
1292    // Service Connection to remote media container service to copy
1293    // package uri's from external media onto secure containers
1294    // or internal storage.
1295    private IMediaContainerService mContainerService = null;
1296
1297    static final int SEND_PENDING_BROADCAST = 1;
1298    static final int MCS_BOUND = 3;
1299    static final int END_COPY = 4;
1300    static final int INIT_COPY = 5;
1301    static final int MCS_UNBIND = 6;
1302    static final int START_CLEANING_PACKAGE = 7;
1303    static final int FIND_INSTALL_LOC = 8;
1304    static final int POST_INSTALL = 9;
1305    static final int MCS_RECONNECT = 10;
1306    static final int MCS_GIVE_UP = 11;
1307    static final int WRITE_SETTINGS = 13;
1308    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1309    static final int PACKAGE_VERIFIED = 15;
1310    static final int CHECK_PENDING_VERIFICATION = 16;
1311    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1312    static final int INTENT_FILTER_VERIFIED = 18;
1313    static final int WRITE_PACKAGE_LIST = 19;
1314    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1315
1316    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1317
1318    // Delay time in millisecs
1319    static final int BROADCAST_DELAY = 10 * 1000;
1320
1321    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1322            2 * 60 * 60 * 1000L; /* two hours */
1323
1324    static UserManagerService sUserManager;
1325
1326    // Stores a list of users whose package restrictions file needs to be updated
1327    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1328
1329    final private DefaultContainerConnection mDefContainerConn =
1330            new DefaultContainerConnection();
1331    class DefaultContainerConnection implements ServiceConnection {
1332        public void onServiceConnected(ComponentName name, IBinder service) {
1333            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1334            final IMediaContainerService imcs = IMediaContainerService.Stub
1335                    .asInterface(Binder.allowBlocking(service));
1336            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1337        }
1338
1339        public void onServiceDisconnected(ComponentName name) {
1340            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1341        }
1342    }
1343
1344    // Recordkeeping of restore-after-install operations that are currently in flight
1345    // between the Package Manager and the Backup Manager
1346    static class PostInstallData {
1347        public InstallArgs args;
1348        public PackageInstalledInfo res;
1349
1350        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1351            args = _a;
1352            res = _r;
1353        }
1354    }
1355
1356    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1357    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1358
1359    // XML tags for backup/restore of various bits of state
1360    private static final String TAG_PREFERRED_BACKUP = "pa";
1361    private static final String TAG_DEFAULT_APPS = "da";
1362    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1363
1364    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1365    private static final String TAG_ALL_GRANTS = "rt-grants";
1366    private static final String TAG_GRANT = "grant";
1367    private static final String ATTR_PACKAGE_NAME = "pkg";
1368
1369    private static final String TAG_PERMISSION = "perm";
1370    private static final String ATTR_PERMISSION_NAME = "name";
1371    private static final String ATTR_IS_GRANTED = "g";
1372    private static final String ATTR_USER_SET = "set";
1373    private static final String ATTR_USER_FIXED = "fixed";
1374    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1375
1376    // System/policy permission grants are not backed up
1377    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1378            FLAG_PERMISSION_POLICY_FIXED
1379            | FLAG_PERMISSION_SYSTEM_FIXED
1380            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1381
1382    // And we back up these user-adjusted states
1383    private static final int USER_RUNTIME_GRANT_MASK =
1384            FLAG_PERMISSION_USER_SET
1385            | FLAG_PERMISSION_USER_FIXED
1386            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1387
1388    final @Nullable String mRequiredVerifierPackage;
1389    final @NonNull String mRequiredInstallerPackage;
1390    final @NonNull String mRequiredUninstallerPackage;
1391    final @Nullable String mSetupWizardPackage;
1392    final @Nullable String mStorageManagerPackage;
1393    final @NonNull String mServicesSystemSharedLibraryPackageName;
1394    final @NonNull String mSharedSystemSharedLibraryPackageName;
1395
1396    private final PackageUsage mPackageUsage = new PackageUsage();
1397    private final CompilerStats mCompilerStats = new CompilerStats();
1398
1399    class PackageHandler extends Handler {
1400        private boolean mBound = false;
1401        final ArrayList<HandlerParams> mPendingInstalls =
1402            new ArrayList<HandlerParams>();
1403
1404        private boolean connectToService() {
1405            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1406                    " DefaultContainerService");
1407            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1408            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1409            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1410                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1411                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1412                mBound = true;
1413                return true;
1414            }
1415            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1416            return false;
1417        }
1418
1419        private void disconnectService() {
1420            mContainerService = null;
1421            mBound = false;
1422            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1423            mContext.unbindService(mDefContainerConn);
1424            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1425        }
1426
1427        PackageHandler(Looper looper) {
1428            super(looper);
1429        }
1430
1431        public void handleMessage(Message msg) {
1432            try {
1433                doHandleMessage(msg);
1434            } finally {
1435                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1436            }
1437        }
1438
1439        void doHandleMessage(Message msg) {
1440            switch (msg.what) {
1441                case INIT_COPY: {
1442                    HandlerParams params = (HandlerParams) msg.obj;
1443                    int idx = mPendingInstalls.size();
1444                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1445                    // If a bind was already initiated we dont really
1446                    // need to do anything. The pending install
1447                    // will be processed later on.
1448                    if (!mBound) {
1449                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1450                                System.identityHashCode(mHandler));
1451                        // If this is the only one pending we might
1452                        // have to bind to the service again.
1453                        if (!connectToService()) {
1454                            Slog.e(TAG, "Failed to bind to media container service");
1455                            params.serviceError();
1456                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1457                                    System.identityHashCode(mHandler));
1458                            if (params.traceMethod != null) {
1459                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1460                                        params.traceCookie);
1461                            }
1462                            return;
1463                        } else {
1464                            // Once we bind to the service, the first
1465                            // pending request will be processed.
1466                            mPendingInstalls.add(idx, params);
1467                        }
1468                    } else {
1469                        mPendingInstalls.add(idx, params);
1470                        // Already bound to the service. Just make
1471                        // sure we trigger off processing the first request.
1472                        if (idx == 0) {
1473                            mHandler.sendEmptyMessage(MCS_BOUND);
1474                        }
1475                    }
1476                    break;
1477                }
1478                case MCS_BOUND: {
1479                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1480                    if (msg.obj != null) {
1481                        mContainerService = (IMediaContainerService) msg.obj;
1482                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1483                                System.identityHashCode(mHandler));
1484                    }
1485                    if (mContainerService == null) {
1486                        if (!mBound) {
1487                            // Something seriously wrong since we are not bound and we are not
1488                            // waiting for connection. Bail out.
1489                            Slog.e(TAG, "Cannot bind to media container service");
1490                            for (HandlerParams params : mPendingInstalls) {
1491                                // Indicate service bind error
1492                                params.serviceError();
1493                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1494                                        System.identityHashCode(params));
1495                                if (params.traceMethod != null) {
1496                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1497                                            params.traceMethod, params.traceCookie);
1498                                }
1499                                return;
1500                            }
1501                            mPendingInstalls.clear();
1502                        } else {
1503                            Slog.w(TAG, "Waiting to connect to media container service");
1504                        }
1505                    } else if (mPendingInstalls.size() > 0) {
1506                        HandlerParams params = mPendingInstalls.get(0);
1507                        if (params != null) {
1508                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1509                                    System.identityHashCode(params));
1510                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1511                            if (params.startCopy()) {
1512                                // We are done...  look for more work or to
1513                                // go idle.
1514                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1515                                        "Checking for more work or unbind...");
1516                                // Delete pending install
1517                                if (mPendingInstalls.size() > 0) {
1518                                    mPendingInstalls.remove(0);
1519                                }
1520                                if (mPendingInstalls.size() == 0) {
1521                                    if (mBound) {
1522                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1523                                                "Posting delayed MCS_UNBIND");
1524                                        removeMessages(MCS_UNBIND);
1525                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1526                                        // Unbind after a little delay, to avoid
1527                                        // continual thrashing.
1528                                        sendMessageDelayed(ubmsg, 10000);
1529                                    }
1530                                } else {
1531                                    // There are more pending requests in queue.
1532                                    // Just post MCS_BOUND message to trigger processing
1533                                    // of next pending install.
1534                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1535                                            "Posting MCS_BOUND for next work");
1536                                    mHandler.sendEmptyMessage(MCS_BOUND);
1537                                }
1538                            }
1539                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1540                        }
1541                    } else {
1542                        // Should never happen ideally.
1543                        Slog.w(TAG, "Empty queue");
1544                    }
1545                    break;
1546                }
1547                case MCS_RECONNECT: {
1548                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1549                    if (mPendingInstalls.size() > 0) {
1550                        if (mBound) {
1551                            disconnectService();
1552                        }
1553                        if (!connectToService()) {
1554                            Slog.e(TAG, "Failed to bind to media container service");
1555                            for (HandlerParams params : mPendingInstalls) {
1556                                // Indicate service bind error
1557                                params.serviceError();
1558                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1559                                        System.identityHashCode(params));
1560                            }
1561                            mPendingInstalls.clear();
1562                        }
1563                    }
1564                    break;
1565                }
1566                case MCS_UNBIND: {
1567                    // If there is no actual work left, then time to unbind.
1568                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1569
1570                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1571                        if (mBound) {
1572                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1573
1574                            disconnectService();
1575                        }
1576                    } else if (mPendingInstalls.size() > 0) {
1577                        // There are more pending requests in queue.
1578                        // Just post MCS_BOUND message to trigger processing
1579                        // of next pending install.
1580                        mHandler.sendEmptyMessage(MCS_BOUND);
1581                    }
1582
1583                    break;
1584                }
1585                case MCS_GIVE_UP: {
1586                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1587                    HandlerParams params = mPendingInstalls.remove(0);
1588                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1589                            System.identityHashCode(params));
1590                    break;
1591                }
1592                case SEND_PENDING_BROADCAST: {
1593                    String packages[];
1594                    ArrayList<String> components[];
1595                    int size = 0;
1596                    int uids[];
1597                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1598                    synchronized (mPackages) {
1599                        if (mPendingBroadcasts == null) {
1600                            return;
1601                        }
1602                        size = mPendingBroadcasts.size();
1603                        if (size <= 0) {
1604                            // Nothing to be done. Just return
1605                            return;
1606                        }
1607                        packages = new String[size];
1608                        components = new ArrayList[size];
1609                        uids = new int[size];
1610                        int i = 0;  // filling out the above arrays
1611
1612                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1613                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1614                            Iterator<Map.Entry<String, ArrayList<String>>> it
1615                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1616                                            .entrySet().iterator();
1617                            while (it.hasNext() && i < size) {
1618                                Map.Entry<String, ArrayList<String>> ent = it.next();
1619                                packages[i] = ent.getKey();
1620                                components[i] = ent.getValue();
1621                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1622                                uids[i] = (ps != null)
1623                                        ? UserHandle.getUid(packageUserId, ps.appId)
1624                                        : -1;
1625                                i++;
1626                            }
1627                        }
1628                        size = i;
1629                        mPendingBroadcasts.clear();
1630                    }
1631                    // Send broadcasts
1632                    for (int i = 0; i < size; i++) {
1633                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1634                    }
1635                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1636                    break;
1637                }
1638                case START_CLEANING_PACKAGE: {
1639                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1640                    final String packageName = (String)msg.obj;
1641                    final int userId = msg.arg1;
1642                    final boolean andCode = msg.arg2 != 0;
1643                    synchronized (mPackages) {
1644                        if (userId == UserHandle.USER_ALL) {
1645                            int[] users = sUserManager.getUserIds();
1646                            for (int user : users) {
1647                                mSettings.addPackageToCleanLPw(
1648                                        new PackageCleanItem(user, packageName, andCode));
1649                            }
1650                        } else {
1651                            mSettings.addPackageToCleanLPw(
1652                                    new PackageCleanItem(userId, packageName, andCode));
1653                        }
1654                    }
1655                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1656                    startCleaningPackages();
1657                } break;
1658                case POST_INSTALL: {
1659                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1660
1661                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1662                    final boolean didRestore = (msg.arg2 != 0);
1663                    mRunningInstalls.delete(msg.arg1);
1664
1665                    if (data != null) {
1666                        InstallArgs args = data.args;
1667                        PackageInstalledInfo parentRes = data.res;
1668
1669                        final boolean grantPermissions = (args.installFlags
1670                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1671                        final boolean killApp = (args.installFlags
1672                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1673                        final boolean virtualPreload = ((args.installFlags
1674                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1675                        final String[] grantedPermissions = args.installGrantPermissions;
1676
1677                        // Handle the parent package
1678                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1679                                virtualPreload, grantedPermissions, didRestore,
1680                                args.installerPackageName, args.observer);
1681
1682                        // Handle the child packages
1683                        final int childCount = (parentRes.addedChildPackages != null)
1684                                ? parentRes.addedChildPackages.size() : 0;
1685                        for (int i = 0; i < childCount; i++) {
1686                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1687                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1688                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1689                                    args.installerPackageName, args.observer);
1690                        }
1691
1692                        // Log tracing if needed
1693                        if (args.traceMethod != null) {
1694                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1695                                    args.traceCookie);
1696                        }
1697                    } else {
1698                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1699                    }
1700
1701                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1702                } break;
1703                case WRITE_SETTINGS: {
1704                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1705                    synchronized (mPackages) {
1706                        removeMessages(WRITE_SETTINGS);
1707                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1708                        mSettings.writeLPr();
1709                        mDirtyUsers.clear();
1710                    }
1711                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1712                } break;
1713                case WRITE_PACKAGE_RESTRICTIONS: {
1714                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1715                    synchronized (mPackages) {
1716                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1717                        for (int userId : mDirtyUsers) {
1718                            mSettings.writePackageRestrictionsLPr(userId);
1719                        }
1720                        mDirtyUsers.clear();
1721                    }
1722                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1723                } break;
1724                case WRITE_PACKAGE_LIST: {
1725                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1726                    synchronized (mPackages) {
1727                        removeMessages(WRITE_PACKAGE_LIST);
1728                        mSettings.writePackageListLPr(msg.arg1);
1729                    }
1730                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1731                } break;
1732                case CHECK_PENDING_VERIFICATION: {
1733                    final int verificationId = msg.arg1;
1734                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1735
1736                    if ((state != null) && !state.timeoutExtended()) {
1737                        final InstallArgs args = state.getInstallArgs();
1738                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1739
1740                        Slog.i(TAG, "Verification timed out for " + originUri);
1741                        mPendingVerification.remove(verificationId);
1742
1743                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1744
1745                        final UserHandle user = args.getUser();
1746                        if (getDefaultVerificationResponse(user)
1747                                == PackageManager.VERIFICATION_ALLOW) {
1748                            Slog.i(TAG, "Continuing with installation of " + originUri);
1749                            state.setVerifierResponse(Binder.getCallingUid(),
1750                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1751                            broadcastPackageVerified(verificationId, originUri,
1752                                    PackageManager.VERIFICATION_ALLOW, user);
1753                            try {
1754                                ret = args.copyApk(mContainerService, true);
1755                            } catch (RemoteException e) {
1756                                Slog.e(TAG, "Could not contact the ContainerService");
1757                            }
1758                        } else {
1759                            broadcastPackageVerified(verificationId, originUri,
1760                                    PackageManager.VERIFICATION_REJECT, user);
1761                        }
1762
1763                        Trace.asyncTraceEnd(
1764                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1765
1766                        processPendingInstall(args, ret);
1767                        mHandler.sendEmptyMessage(MCS_UNBIND);
1768                    }
1769                    break;
1770                }
1771                case PACKAGE_VERIFIED: {
1772                    final int verificationId = msg.arg1;
1773
1774                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1775                    if (state == null) {
1776                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1777                        break;
1778                    }
1779
1780                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1781
1782                    state.setVerifierResponse(response.callerUid, response.code);
1783
1784                    if (state.isVerificationComplete()) {
1785                        mPendingVerification.remove(verificationId);
1786
1787                        final InstallArgs args = state.getInstallArgs();
1788                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1789
1790                        int ret;
1791                        if (state.isInstallAllowed()) {
1792                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1793                            broadcastPackageVerified(verificationId, originUri,
1794                                    response.code, state.getInstallArgs().getUser());
1795                            try {
1796                                ret = args.copyApk(mContainerService, true);
1797                            } catch (RemoteException e) {
1798                                Slog.e(TAG, "Could not contact the ContainerService");
1799                            }
1800                        } else {
1801                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1802                        }
1803
1804                        Trace.asyncTraceEnd(
1805                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1806
1807                        processPendingInstall(args, ret);
1808                        mHandler.sendEmptyMessage(MCS_UNBIND);
1809                    }
1810
1811                    break;
1812                }
1813                case START_INTENT_FILTER_VERIFICATIONS: {
1814                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1815                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1816                            params.replacing, params.pkg);
1817                    break;
1818                }
1819                case INTENT_FILTER_VERIFIED: {
1820                    final int verificationId = msg.arg1;
1821
1822                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1823                            verificationId);
1824                    if (state == null) {
1825                        Slog.w(TAG, "Invalid IntentFilter verification token "
1826                                + verificationId + " received");
1827                        break;
1828                    }
1829
1830                    final int userId = state.getUserId();
1831
1832                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1833                            "Processing IntentFilter verification with token:"
1834                            + verificationId + " and userId:" + userId);
1835
1836                    final IntentFilterVerificationResponse response =
1837                            (IntentFilterVerificationResponse) msg.obj;
1838
1839                    state.setVerifierResponse(response.callerUid, response.code);
1840
1841                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1842                            "IntentFilter verification with token:" + verificationId
1843                            + " and userId:" + userId
1844                            + " is settings verifier response with response code:"
1845                            + response.code);
1846
1847                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1848                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1849                                + response.getFailedDomainsString());
1850                    }
1851
1852                    if (state.isVerificationComplete()) {
1853                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1854                    } else {
1855                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1856                                "IntentFilter verification with token:" + verificationId
1857                                + " was not said to be complete");
1858                    }
1859
1860                    break;
1861                }
1862                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1863                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1864                            mInstantAppResolverConnection,
1865                            (InstantAppRequest) msg.obj,
1866                            mInstantAppInstallerActivity,
1867                            mHandler);
1868                }
1869            }
1870        }
1871    }
1872
1873    private PermissionCallback mPermissionCallback = new PermissionCallback() {
1874        @Override
1875        public void onGidsChanged(int appId, int userId) {
1876            mHandler.post(new Runnable() {
1877                @Override
1878                public void run() {
1879                    killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
1880                }
1881            });
1882        }
1883        @Override
1884        public void onPermissionGranted(int uid, int userId) {
1885            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1886
1887            // Not critical; if this is lost, the application has to request again.
1888            synchronized (mPackages) {
1889                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1890            }
1891        }
1892        @Override
1893        public void onInstallPermissionGranted() {
1894            synchronized (mPackages) {
1895                scheduleWriteSettingsLocked();
1896            }
1897        }
1898        @Override
1899        public void onPermissionRevoked(int uid, int userId) {
1900            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1901
1902            synchronized (mPackages) {
1903                // Critical; after this call the application should never have the permission
1904                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
1905            }
1906
1907            final int appId = UserHandle.getAppId(uid);
1908            killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
1909        }
1910        @Override
1911        public void onInstallPermissionRevoked() {
1912            synchronized (mPackages) {
1913                scheduleWriteSettingsLocked();
1914            }
1915        }
1916        @Override
1917        public void onPermissionUpdated(int[] updatedUserIds, boolean sync) {
1918            synchronized (mPackages) {
1919                for (int userId : updatedUserIds) {
1920                    mSettings.writeRuntimePermissionsForUserLPr(userId, sync);
1921                }
1922            }
1923        }
1924        @Override
1925        public void onInstallPermissionUpdated() {
1926            synchronized (mPackages) {
1927                scheduleWriteSettingsLocked();
1928            }
1929        }
1930        @Override
1931        public void onPermissionRemoved() {
1932            synchronized (mPackages) {
1933                mSettings.writeLPr();
1934            }
1935        }
1936    };
1937
1938    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1939            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1940            boolean launchedForRestore, String installerPackage,
1941            IPackageInstallObserver2 installObserver) {
1942        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1943            // Send the removed broadcasts
1944            if (res.removedInfo != null) {
1945                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1946            }
1947
1948            // Now that we successfully installed the package, grant runtime
1949            // permissions if requested before broadcasting the install. Also
1950            // for legacy apps in permission review mode we clear the permission
1951            // review flag which is used to emulate runtime permissions for
1952            // legacy apps.
1953            if (grantPermissions) {
1954                final int callingUid = Binder.getCallingUid();
1955                mPermissionManager.grantRequestedRuntimePermissions(
1956                        res.pkg, res.newUsers, grantedPermissions, callingUid,
1957                        mPermissionCallback);
1958            }
1959
1960            final boolean update = res.removedInfo != null
1961                    && res.removedInfo.removedPackage != null;
1962            final String installerPackageName =
1963                    res.installerPackageName != null
1964                            ? res.installerPackageName
1965                            : res.removedInfo != null
1966                                    ? res.removedInfo.installerPackageName
1967                                    : null;
1968
1969            // If this is the first time we have child packages for a disabled privileged
1970            // app that had no children, we grant requested runtime permissions to the new
1971            // children if the parent on the system image had them already granted.
1972            if (res.pkg.parentPackage != null) {
1973                final int callingUid = Binder.getCallingUid();
1974                mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage(
1975                        res.pkg, callingUid, mPermissionCallback);
1976            }
1977
1978            synchronized (mPackages) {
1979                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1980            }
1981
1982            final String packageName = res.pkg.applicationInfo.packageName;
1983
1984            // Determine the set of users who are adding this package for
1985            // the first time vs. those who are seeing an update.
1986            int[] firstUserIds = EMPTY_INT_ARRAY;
1987            int[] firstInstantUserIds = EMPTY_INT_ARRAY;
1988            int[] updateUserIds = EMPTY_INT_ARRAY;
1989            int[] instantUserIds = EMPTY_INT_ARRAY;
1990            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1991            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1992            for (int newUser : res.newUsers) {
1993                final boolean isInstantApp = ps.getInstantApp(newUser);
1994                if (allNewUsers) {
1995                    if (isInstantApp) {
1996                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
1997                    } else {
1998                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
1999                    }
2000                    continue;
2001                }
2002                boolean isNew = true;
2003                for (int origUser : res.origUsers) {
2004                    if (origUser == newUser) {
2005                        isNew = false;
2006                        break;
2007                    }
2008                }
2009                if (isNew) {
2010                    if (isInstantApp) {
2011                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2012                    } else {
2013                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2014                    }
2015                } else {
2016                    if (isInstantApp) {
2017                        instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser);
2018                    } else {
2019                        updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser);
2020                    }
2021                }
2022            }
2023
2024            // Send installed broadcasts if the package is not a static shared lib.
2025            if (res.pkg.staticSharedLibName == null) {
2026                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
2027
2028                // Send added for users that see the package for the first time
2029                // sendPackageAddedForNewUsers also deals with system apps
2030                int appId = UserHandle.getAppId(res.uid);
2031                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
2032                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
2033                        virtualPreload /*startReceiver*/, appId, firstUserIds, firstInstantUserIds);
2034
2035                // Send added for users that don't see the package for the first time
2036                Bundle extras = new Bundle(1);
2037                extras.putInt(Intent.EXTRA_UID, res.uid);
2038                if (update) {
2039                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2040                }
2041                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2042                        extras, 0 /*flags*/,
2043                        null /*targetPackage*/, null /*finishedReceiver*/,
2044                        updateUserIds, instantUserIds);
2045                if (installerPackageName != null) {
2046                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2047                            extras, 0 /*flags*/,
2048                            installerPackageName, null /*finishedReceiver*/,
2049                            updateUserIds, instantUserIds);
2050                }
2051
2052                // Send replaced for users that don't see the package for the first time
2053                if (update) {
2054                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2055                            packageName, extras, 0 /*flags*/,
2056                            null /*targetPackage*/, null /*finishedReceiver*/,
2057                            updateUserIds, instantUserIds);
2058                    if (installerPackageName != null) {
2059                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2060                                extras, 0 /*flags*/,
2061                                installerPackageName, null /*finishedReceiver*/,
2062                                updateUserIds, instantUserIds);
2063                    }
2064                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2065                            null /*package*/, null /*extras*/, 0 /*flags*/,
2066                            packageName /*targetPackage*/,
2067                            null /*finishedReceiver*/, updateUserIds, instantUserIds);
2068                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2069                    // First-install and we did a restore, so we're responsible for the
2070                    // first-launch broadcast.
2071                    if (DEBUG_BACKUP) {
2072                        Slog.i(TAG, "Post-restore of " + packageName
2073                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds));
2074                    }
2075                    sendFirstLaunchBroadcast(packageName, installerPackage,
2076                            firstUserIds, firstInstantUserIds);
2077                }
2078
2079                // Send broadcast package appeared if forward locked/external for all users
2080                // treat asec-hosted packages like removable media on upgrade
2081                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2082                    if (DEBUG_INSTALL) {
2083                        Slog.i(TAG, "upgrading pkg " + res.pkg
2084                                + " is ASEC-hosted -> AVAILABLE");
2085                    }
2086                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2087                    ArrayList<String> pkgList = new ArrayList<>(1);
2088                    pkgList.add(packageName);
2089                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2090                }
2091            }
2092
2093            // Work that needs to happen on first install within each user
2094            if (firstUserIds != null && firstUserIds.length > 0) {
2095                synchronized (mPackages) {
2096                    for (int userId : firstUserIds) {
2097                        // If this app is a browser and it's newly-installed for some
2098                        // users, clear any default-browser state in those users. The
2099                        // app's nature doesn't depend on the user, so we can just check
2100                        // its browser nature in any user and generalize.
2101                        if (packageIsBrowser(packageName, userId)) {
2102                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2103                        }
2104
2105                        // We may also need to apply pending (restored) runtime
2106                        // permission grants within these users.
2107                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2108                    }
2109                }
2110            }
2111
2112            if (allNewUsers && !update) {
2113                notifyPackageAdded(packageName);
2114            }
2115
2116            // Log current value of "unknown sources" setting
2117            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2118                    getUnknownSourcesSettings());
2119
2120            // Remove the replaced package's older resources safely now
2121            // We delete after a gc for applications  on sdcard.
2122            if (res.removedInfo != null && res.removedInfo.args != null) {
2123                Runtime.getRuntime().gc();
2124                synchronized (mInstallLock) {
2125                    res.removedInfo.args.doPostDeleteLI(true);
2126                }
2127            } else {
2128                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2129                // and not block here.
2130                VMRuntime.getRuntime().requestConcurrentGC();
2131            }
2132
2133            // Notify DexManager that the package was installed for new users.
2134            // The updated users should already be indexed and the package code paths
2135            // should not change.
2136            // Don't notify the manager for ephemeral apps as they are not expected to
2137            // survive long enough to benefit of background optimizations.
2138            for (int userId : firstUserIds) {
2139                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2140                // There's a race currently where some install events may interleave with an uninstall.
2141                // This can lead to package info being null (b/36642664).
2142                if (info != null) {
2143                    mDexManager.notifyPackageInstalled(info, userId);
2144                }
2145            }
2146        }
2147
2148        // If someone is watching installs - notify them
2149        if (installObserver != null) {
2150            try {
2151                Bundle extras = extrasForInstallResult(res);
2152                installObserver.onPackageInstalled(res.name, res.returnCode,
2153                        res.returnMsg, extras);
2154            } catch (RemoteException e) {
2155                Slog.i(TAG, "Observer no longer exists.");
2156            }
2157        }
2158    }
2159
2160    private StorageEventListener mStorageListener = new StorageEventListener() {
2161        @Override
2162        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2163            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2164                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2165                    final String volumeUuid = vol.getFsUuid();
2166
2167                    // Clean up any users or apps that were removed or recreated
2168                    // while this volume was missing
2169                    sUserManager.reconcileUsers(volumeUuid);
2170                    reconcileApps(volumeUuid);
2171
2172                    // Clean up any install sessions that expired or were
2173                    // cancelled while this volume was missing
2174                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2175
2176                    loadPrivatePackages(vol);
2177
2178                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2179                    unloadPrivatePackages(vol);
2180                }
2181            }
2182        }
2183
2184        @Override
2185        public void onVolumeForgotten(String fsUuid) {
2186            if (TextUtils.isEmpty(fsUuid)) {
2187                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2188                return;
2189            }
2190
2191            // Remove any apps installed on the forgotten volume
2192            synchronized (mPackages) {
2193                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2194                for (PackageSetting ps : packages) {
2195                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2196                    deletePackageVersioned(new VersionedPackage(ps.name,
2197                            PackageManager.VERSION_CODE_HIGHEST),
2198                            new LegacyPackageDeleteObserver(null).getBinder(),
2199                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2200                    // Try very hard to release any references to this package
2201                    // so we don't risk the system server being killed due to
2202                    // open FDs
2203                    AttributeCache.instance().removePackage(ps.name);
2204                }
2205
2206                mSettings.onVolumeForgotten(fsUuid);
2207                mSettings.writeLPr();
2208            }
2209        }
2210    };
2211
2212    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2213        Bundle extras = null;
2214        switch (res.returnCode) {
2215            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2216                extras = new Bundle();
2217                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2218                        res.origPermission);
2219                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2220                        res.origPackage);
2221                break;
2222            }
2223            case PackageManager.INSTALL_SUCCEEDED: {
2224                extras = new Bundle();
2225                extras.putBoolean(Intent.EXTRA_REPLACING,
2226                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2227                break;
2228            }
2229        }
2230        return extras;
2231    }
2232
2233    void scheduleWriteSettingsLocked() {
2234        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2235            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2236        }
2237    }
2238
2239    void scheduleWritePackageListLocked(int userId) {
2240        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2241            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2242            msg.arg1 = userId;
2243            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2244        }
2245    }
2246
2247    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2248        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2249        scheduleWritePackageRestrictionsLocked(userId);
2250    }
2251
2252    void scheduleWritePackageRestrictionsLocked(int userId) {
2253        final int[] userIds = (userId == UserHandle.USER_ALL)
2254                ? sUserManager.getUserIds() : new int[]{userId};
2255        for (int nextUserId : userIds) {
2256            if (!sUserManager.exists(nextUserId)) return;
2257            mDirtyUsers.add(nextUserId);
2258            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2259                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2260            }
2261        }
2262    }
2263
2264    public static PackageManagerService main(Context context, Installer installer,
2265            boolean factoryTest, boolean onlyCore) {
2266        // Self-check for initial settings.
2267        PackageManagerServiceCompilerMapping.checkProperties();
2268
2269        PackageManagerService m = new PackageManagerService(context, installer,
2270                factoryTest, onlyCore);
2271        m.enableSystemUserPackages();
2272        ServiceManager.addService("package", m);
2273        final PackageManagerNative pmn = m.new PackageManagerNative();
2274        ServiceManager.addService("package_native", pmn);
2275        return m;
2276    }
2277
2278    private void enableSystemUserPackages() {
2279        if (!UserManager.isSplitSystemUser()) {
2280            return;
2281        }
2282        // For system user, enable apps based on the following conditions:
2283        // - app is whitelisted or belong to one of these groups:
2284        //   -- system app which has no launcher icons
2285        //   -- system app which has INTERACT_ACROSS_USERS permission
2286        //   -- system IME app
2287        // - app is not in the blacklist
2288        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2289        Set<String> enableApps = new ArraySet<>();
2290        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2291                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2292                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2293        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2294        enableApps.addAll(wlApps);
2295        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2296                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2297        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2298        enableApps.removeAll(blApps);
2299        Log.i(TAG, "Applications installed for system user: " + enableApps);
2300        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2301                UserHandle.SYSTEM);
2302        final int allAppsSize = allAps.size();
2303        synchronized (mPackages) {
2304            for (int i = 0; i < allAppsSize; i++) {
2305                String pName = allAps.get(i);
2306                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2307                // Should not happen, but we shouldn't be failing if it does
2308                if (pkgSetting == null) {
2309                    continue;
2310                }
2311                boolean install = enableApps.contains(pName);
2312                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2313                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2314                            + " for system user");
2315                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2316                }
2317            }
2318            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2319        }
2320    }
2321
2322    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2323        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2324                Context.DISPLAY_SERVICE);
2325        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2326    }
2327
2328    /**
2329     * Requests that files preopted on a secondary system partition be copied to the data partition
2330     * if possible.  Note that the actual copying of the files is accomplished by init for security
2331     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2332     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2333     */
2334    private static void requestCopyPreoptedFiles() {
2335        final int WAIT_TIME_MS = 100;
2336        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2337        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2338            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2339            // We will wait for up to 100 seconds.
2340            final long timeStart = SystemClock.uptimeMillis();
2341            final long timeEnd = timeStart + 100 * 1000;
2342            long timeNow = timeStart;
2343            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2344                try {
2345                    Thread.sleep(WAIT_TIME_MS);
2346                } catch (InterruptedException e) {
2347                    // Do nothing
2348                }
2349                timeNow = SystemClock.uptimeMillis();
2350                if (timeNow > timeEnd) {
2351                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2352                    Slog.wtf(TAG, "cppreopt did not finish!");
2353                    break;
2354                }
2355            }
2356
2357            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2358        }
2359    }
2360
2361    public PackageManagerService(Context context, Installer installer,
2362            boolean factoryTest, boolean onlyCore) {
2363        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2364        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2365        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2366                SystemClock.uptimeMillis());
2367
2368        if (mSdkVersion <= 0) {
2369            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2370        }
2371
2372        mContext = context;
2373
2374        mFactoryTest = factoryTest;
2375        mOnlyCore = onlyCore;
2376        mMetrics = new DisplayMetrics();
2377        mInstaller = installer;
2378
2379        // Create sub-components that provide services / data. Order here is important.
2380        synchronized (mInstallLock) {
2381        synchronized (mPackages) {
2382            // Expose private service for system components to use.
2383            LocalServices.addService(
2384                    PackageManagerInternal.class, new PackageManagerInternalImpl());
2385            sUserManager = new UserManagerService(context, this,
2386                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2387            mPermissionManager = PermissionManagerService.create(context,
2388                    new DefaultPermissionGrantedCallback() {
2389                        @Override
2390                        public void onDefaultRuntimePermissionsGranted(int userId) {
2391                            synchronized(mPackages) {
2392                                mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);
2393                            }
2394                        }
2395                    }, mPackages /*externalLock*/);
2396            mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy();
2397            mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages);
2398        }
2399        }
2400        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2401                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2402        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2403                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2404        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2405                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2406        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2407                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2408        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2409                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2410        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2411                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2412        mSettings.addSharedUserLPw("android.uid.se", SE_UID,
2413                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2414
2415        String separateProcesses = SystemProperties.get("debug.separate_processes");
2416        if (separateProcesses != null && separateProcesses.length() > 0) {
2417            if ("*".equals(separateProcesses)) {
2418                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2419                mSeparateProcesses = null;
2420                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2421            } else {
2422                mDefParseFlags = 0;
2423                mSeparateProcesses = separateProcesses.split(",");
2424                Slog.w(TAG, "Running with debug.separate_processes: "
2425                        + separateProcesses);
2426            }
2427        } else {
2428            mDefParseFlags = 0;
2429            mSeparateProcesses = null;
2430        }
2431
2432        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2433                "*dexopt*");
2434        DexManager.Listener dexManagerListener = DexLogger.getListener(this,
2435                installer, mInstallLock);
2436        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock,
2437                dexManagerListener);
2438        mArtManagerService = new ArtManagerService(this, installer, mInstallLock);
2439        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2440
2441        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2442                FgThread.get().getLooper());
2443
2444        getDefaultDisplayMetrics(context, mMetrics);
2445
2446        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2447        SystemConfig systemConfig = SystemConfig.getInstance();
2448        mAvailableFeatures = systemConfig.getAvailableFeatures();
2449        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2450
2451        mProtectedPackages = new ProtectedPackages(mContext);
2452
2453        synchronized (mInstallLock) {
2454        // writer
2455        synchronized (mPackages) {
2456            mHandlerThread = new ServiceThread(TAG,
2457                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2458            mHandlerThread.start();
2459            mHandler = new PackageHandler(mHandlerThread.getLooper());
2460            mProcessLoggingHandler = new ProcessLoggingHandler();
2461            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2462            mInstantAppRegistry = new InstantAppRegistry(this);
2463
2464            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2465            final int builtInLibCount = libConfig.size();
2466            for (int i = 0; i < builtInLibCount; i++) {
2467                String name = libConfig.keyAt(i);
2468                String path = libConfig.valueAt(i);
2469                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2470                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2471            }
2472
2473            SELinuxMMAC.readInstallPolicy();
2474
2475            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2476            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2477            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2478
2479            // Clean up orphaned packages for which the code path doesn't exist
2480            // and they are an update to a system app - caused by bug/32321269
2481            final int packageSettingCount = mSettings.mPackages.size();
2482            for (int i = packageSettingCount - 1; i >= 0; i--) {
2483                PackageSetting ps = mSettings.mPackages.valueAt(i);
2484                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2485                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2486                    mSettings.mPackages.removeAt(i);
2487                    mSettings.enableSystemPackageLPw(ps.name);
2488                }
2489            }
2490
2491            if (mFirstBoot) {
2492                requestCopyPreoptedFiles();
2493            }
2494
2495            String customResolverActivity = Resources.getSystem().getString(
2496                    R.string.config_customResolverActivity);
2497            if (TextUtils.isEmpty(customResolverActivity)) {
2498                customResolverActivity = null;
2499            } else {
2500                mCustomResolverComponentName = ComponentName.unflattenFromString(
2501                        customResolverActivity);
2502            }
2503
2504            long startTime = SystemClock.uptimeMillis();
2505
2506            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2507                    startTime);
2508
2509            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2510            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2511
2512            if (bootClassPath == null) {
2513                Slog.w(TAG, "No BOOTCLASSPATH found!");
2514            }
2515
2516            if (systemServerClassPath == null) {
2517                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2518            }
2519
2520            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2521
2522            final VersionInfo ver = mSettings.getInternalVersion();
2523            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2524            if (mIsUpgrade) {
2525                logCriticalInfo(Log.INFO,
2526                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2527            }
2528
2529            // when upgrading from pre-M, promote system app permissions from install to runtime
2530            mPromoteSystemApps =
2531                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2532
2533            // When upgrading from pre-N, we need to handle package extraction like first boot,
2534            // as there is no profiling data available.
2535            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2536
2537            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2538
2539            // save off the names of pre-existing system packages prior to scanning; we don't
2540            // want to automatically grant runtime permissions for new system apps
2541            if (mPromoteSystemApps) {
2542                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2543                while (pkgSettingIter.hasNext()) {
2544                    PackageSetting ps = pkgSettingIter.next();
2545                    if (isSystemApp(ps)) {
2546                        mExistingSystemPackages.add(ps.name);
2547                    }
2548                }
2549            }
2550
2551            mCacheDir = preparePackageParserCache(mIsUpgrade);
2552
2553            // Set flag to monitor and not change apk file paths when
2554            // scanning install directories.
2555            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2556
2557            if (mIsUpgrade || mFirstBoot) {
2558                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2559            }
2560
2561            // Collect vendor/product overlay packages. (Do this before scanning any apps.)
2562            // For security and version matching reason, only consider
2563            // overlay packages if they reside in the right directory.
2564            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR),
2565                    mDefParseFlags
2566                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2567                    scanFlags
2568                    | SCAN_AS_SYSTEM
2569                    | SCAN_AS_VENDOR,
2570                    0);
2571            scanDirTracedLI(new File(PRODUCT_OVERLAY_DIR),
2572                    mDefParseFlags
2573                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2574                    scanFlags
2575                    | SCAN_AS_SYSTEM
2576                    | SCAN_AS_PRODUCT,
2577                    0);
2578
2579            mParallelPackageParserCallback.findStaticOverlayPackages();
2580
2581            // Find base frameworks (resource packages without code).
2582            scanDirTracedLI(frameworkDir,
2583                    mDefParseFlags
2584                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2585                    scanFlags
2586                    | SCAN_NO_DEX
2587                    | SCAN_AS_SYSTEM
2588                    | SCAN_AS_PRIVILEGED,
2589                    0);
2590
2591            // Collected privileged system packages.
2592            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2593            scanDirTracedLI(privilegedAppDir,
2594                    mDefParseFlags
2595                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2596                    scanFlags
2597                    | SCAN_AS_SYSTEM
2598                    | SCAN_AS_PRIVILEGED,
2599                    0);
2600
2601            // Collect ordinary system packages.
2602            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2603            scanDirTracedLI(systemAppDir,
2604                    mDefParseFlags
2605                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2606                    scanFlags
2607                    | SCAN_AS_SYSTEM,
2608                    0);
2609
2610            // Collected privileged vendor packages.
2611            File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
2612            try {
2613                privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile();
2614            } catch (IOException e) {
2615                // failed to look up canonical path, continue with original one
2616            }
2617            scanDirTracedLI(privilegedVendorAppDir,
2618                    mDefParseFlags
2619                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2620                    scanFlags
2621                    | SCAN_AS_SYSTEM
2622                    | SCAN_AS_VENDOR
2623                    | SCAN_AS_PRIVILEGED,
2624                    0);
2625
2626            // Collect ordinary vendor packages.
2627            File vendorAppDir = new File(Environment.getVendorDirectory(), "app");
2628            try {
2629                vendorAppDir = vendorAppDir.getCanonicalFile();
2630            } catch (IOException e) {
2631                // failed to look up canonical path, continue with original one
2632            }
2633            scanDirTracedLI(vendorAppDir,
2634                    mDefParseFlags
2635                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2636                    scanFlags
2637                    | SCAN_AS_SYSTEM
2638                    | SCAN_AS_VENDOR,
2639                    0);
2640
2641            // Collect all OEM packages.
2642            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2643            scanDirTracedLI(oemAppDir,
2644                    mDefParseFlags
2645                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2646                    scanFlags
2647                    | SCAN_AS_SYSTEM
2648                    | SCAN_AS_OEM,
2649                    0);
2650
2651            // Collected privileged product packages.
2652            File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
2653            try {
2654                privilegedProductAppDir = privilegedProductAppDir.getCanonicalFile();
2655            } catch (IOException e) {
2656                // failed to look up canonical path, continue with original one
2657            }
2658            scanDirTracedLI(privilegedProductAppDir,
2659                    mDefParseFlags
2660                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2661                    scanFlags
2662                    | SCAN_AS_SYSTEM
2663                    | SCAN_AS_PRODUCT
2664                    | SCAN_AS_PRIVILEGED,
2665                    0);
2666
2667            // Collect ordinary product packages.
2668            File productAppDir = new File(Environment.getProductDirectory(), "app");
2669            try {
2670                productAppDir = productAppDir.getCanonicalFile();
2671            } catch (IOException e) {
2672                // failed to look up canonical path, continue with original one
2673            }
2674            scanDirTracedLI(productAppDir,
2675                    mDefParseFlags
2676                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2677                    scanFlags
2678                    | SCAN_AS_SYSTEM
2679                    | SCAN_AS_PRODUCT,
2680                    0);
2681
2682            // Prune any system packages that no longer exist.
2683            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2684            // Stub packages must either be replaced with full versions in the /data
2685            // partition or be disabled.
2686            final List<String> stubSystemApps = new ArrayList<>();
2687            if (!mOnlyCore) {
2688                // do this first before mucking with mPackages for the "expecting better" case
2689                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2690                while (pkgIterator.hasNext()) {
2691                    final PackageParser.Package pkg = pkgIterator.next();
2692                    if (pkg.isStub) {
2693                        stubSystemApps.add(pkg.packageName);
2694                    }
2695                }
2696
2697                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2698                while (psit.hasNext()) {
2699                    PackageSetting ps = psit.next();
2700
2701                    /*
2702                     * If this is not a system app, it can't be a
2703                     * disable system app.
2704                     */
2705                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2706                        continue;
2707                    }
2708
2709                    /*
2710                     * If the package is scanned, it's not erased.
2711                     */
2712                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2713                    if (scannedPkg != null) {
2714                        /*
2715                         * If the system app is both scanned and in the
2716                         * disabled packages list, then it must have been
2717                         * added via OTA. Remove it from the currently
2718                         * scanned package so the previously user-installed
2719                         * application can be scanned.
2720                         */
2721                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2722                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2723                                    + ps.name + "; removing system app.  Last known codePath="
2724                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2725                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2726                                    + scannedPkg.getLongVersionCode());
2727                            removePackageLI(scannedPkg, true);
2728                            mExpectingBetter.put(ps.name, ps.codePath);
2729                        }
2730
2731                        continue;
2732                    }
2733
2734                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2735                        psit.remove();
2736                        logCriticalInfo(Log.WARN, "System package " + ps.name
2737                                + " no longer exists; it's data will be wiped");
2738                        // Actual deletion of code and data will be handled by later
2739                        // reconciliation step
2740                    } else {
2741                        // we still have a disabled system package, but, it still might have
2742                        // been removed. check the code path still exists and check there's
2743                        // still a package. the latter can happen if an OTA keeps the same
2744                        // code path, but, changes the package name.
2745                        final PackageSetting disabledPs =
2746                                mSettings.getDisabledSystemPkgLPr(ps.name);
2747                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2748                                || disabledPs.pkg == null) {
2749if (REFACTOR_DEBUG) {
2750Slog.e("TODD",
2751        "Possibly deleted app: " + ps.dumpState_temp()
2752        + "; path: " + (disabledPs.codePath == null ? "<<NULL>>":disabledPs.codePath)
2753        + "; pkg: " + (disabledPs.pkg==null?"<<NULL>>":disabledPs.pkg.toString()));
2754}
2755                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2756                        }
2757                    }
2758                }
2759            }
2760
2761            //look for any incomplete package installations
2762            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2763            for (int i = 0; i < deletePkgsList.size(); i++) {
2764                // Actual deletion of code and data will be handled by later
2765                // reconciliation step
2766                final String packageName = deletePkgsList.get(i).name;
2767                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2768                synchronized (mPackages) {
2769                    mSettings.removePackageLPw(packageName);
2770                }
2771            }
2772
2773            //delete tmp files
2774            deleteTempPackageFiles();
2775
2776            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2777
2778            // Remove any shared userIDs that have no associated packages
2779            mSettings.pruneSharedUsersLPw();
2780            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2781            final int systemPackagesCount = mPackages.size();
2782            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2783                    + " ms, packageCount: " + systemPackagesCount
2784                    + " , timePerPackage: "
2785                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2786                    + " , cached: " + cachedSystemApps);
2787            if (mIsUpgrade && systemPackagesCount > 0) {
2788                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2789                        ((int) systemScanTime) / systemPackagesCount);
2790            }
2791            if (!mOnlyCore) {
2792                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2793                        SystemClock.uptimeMillis());
2794                scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2795
2796                scanDirTracedLI(sDrmAppPrivateInstallDir, mDefParseFlags
2797                        | PackageParser.PARSE_FORWARD_LOCK,
2798                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2799
2800                // Remove disable package settings for updated system apps that were
2801                // removed via an OTA. If the update is no longer present, remove the
2802                // app completely. Otherwise, revoke their system privileges.
2803                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2804                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2805                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2806if (REFACTOR_DEBUG) {
2807Slog.e("TODD",
2808        "remove update; name: " + deletedAppName + ", exists? " + (deletedPkg != null));
2809}
2810                    final String msg;
2811                    if (deletedPkg == null) {
2812                        // should have found an update, but, we didn't; remove everything
2813                        msg = "Updated system package " + deletedAppName
2814                                + " no longer exists; removing its data";
2815                        // Actual deletion of code and data will be handled by later
2816                        // reconciliation step
2817                    } else {
2818                        // found an update; revoke system privileges
2819                        msg = "Updated system package + " + deletedAppName
2820                                + " no longer exists; revoking system privileges";
2821
2822                        // Don't do anything if a stub is removed from the system image. If
2823                        // we were to remove the uncompressed version from the /data partition,
2824                        // this is where it'd be done.
2825
2826                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2827                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2828                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2829                    }
2830                    logCriticalInfo(Log.WARN, msg);
2831                }
2832
2833                /*
2834                 * Make sure all system apps that we expected to appear on
2835                 * the userdata partition actually showed up. If they never
2836                 * appeared, crawl back and revive the system version.
2837                 */
2838                for (int i = 0; i < mExpectingBetter.size(); i++) {
2839                    final String packageName = mExpectingBetter.keyAt(i);
2840                    if (!mPackages.containsKey(packageName)) {
2841                        final File scanFile = mExpectingBetter.valueAt(i);
2842
2843                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2844                                + " but never showed up; reverting to system");
2845
2846                        final @ParseFlags int reparseFlags;
2847                        final @ScanFlags int rescanFlags;
2848                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2849                            reparseFlags =
2850                                    mDefParseFlags |
2851                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2852                            rescanFlags =
2853                                    scanFlags
2854                                    | SCAN_AS_SYSTEM
2855                                    | SCAN_AS_PRIVILEGED;
2856                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2857                            reparseFlags =
2858                                    mDefParseFlags |
2859                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2860                            rescanFlags =
2861                                    scanFlags
2862                                    | SCAN_AS_SYSTEM;
2863                        } else if (FileUtils.contains(privilegedVendorAppDir, scanFile)) {
2864                            reparseFlags =
2865                                    mDefParseFlags |
2866                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2867                            rescanFlags =
2868                                    scanFlags
2869                                    | SCAN_AS_SYSTEM
2870                                    | SCAN_AS_VENDOR
2871                                    | SCAN_AS_PRIVILEGED;
2872                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2873                            reparseFlags =
2874                                    mDefParseFlags |
2875                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2876                            rescanFlags =
2877                                    scanFlags
2878                                    | SCAN_AS_SYSTEM
2879                                    | SCAN_AS_VENDOR;
2880                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2881                            reparseFlags =
2882                                    mDefParseFlags |
2883                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2884                            rescanFlags =
2885                                    scanFlags
2886                                    | SCAN_AS_SYSTEM
2887                                    | SCAN_AS_OEM;
2888                        } else if (FileUtils.contains(privilegedProductAppDir, scanFile)) {
2889                            reparseFlags =
2890                                    mDefParseFlags |
2891                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2892                            rescanFlags =
2893                                    scanFlags
2894                                    | SCAN_AS_SYSTEM
2895                                    | SCAN_AS_PRODUCT
2896                                    | SCAN_AS_PRIVILEGED;
2897                        } else if (FileUtils.contains(productAppDir, scanFile)) {
2898                            reparseFlags =
2899                                    mDefParseFlags |
2900                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2901                            rescanFlags =
2902                                    scanFlags
2903                                    | SCAN_AS_SYSTEM
2904                                    | SCAN_AS_PRODUCT;
2905                        } else {
2906                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2907                            continue;
2908                        }
2909
2910                        mSettings.enableSystemPackageLPw(packageName);
2911
2912                        try {
2913                            scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null);
2914                        } catch (PackageManagerException e) {
2915                            Slog.e(TAG, "Failed to parse original system package: "
2916                                    + e.getMessage());
2917                        }
2918                    }
2919                }
2920
2921                // Uncompress and install any stubbed system applications.
2922                // This must be done last to ensure all stubs are replaced or disabled.
2923                decompressSystemApplications(stubSystemApps, scanFlags);
2924
2925                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2926                                - cachedSystemApps;
2927
2928                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2929                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2930                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2931                        + " ms, packageCount: " + dataPackagesCount
2932                        + " , timePerPackage: "
2933                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2934                        + " , cached: " + cachedNonSystemApps);
2935                if (mIsUpgrade && dataPackagesCount > 0) {
2936                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2937                            ((int) dataScanTime) / dataPackagesCount);
2938                }
2939            }
2940            mExpectingBetter.clear();
2941
2942            // Resolve the storage manager.
2943            mStorageManagerPackage = getStorageManagerPackageName();
2944
2945            // Resolve protected action filters. Only the setup wizard is allowed to
2946            // have a high priority filter for these actions.
2947            mSetupWizardPackage = getSetupWizardPackageName();
2948            if (mProtectedFilters.size() > 0) {
2949                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2950                    Slog.i(TAG, "No setup wizard;"
2951                        + " All protected intents capped to priority 0");
2952                }
2953                for (ActivityIntentInfo filter : mProtectedFilters) {
2954                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2955                        if (DEBUG_FILTERS) {
2956                            Slog.i(TAG, "Found setup wizard;"
2957                                + " allow priority " + filter.getPriority() + ";"
2958                                + " package: " + filter.activity.info.packageName
2959                                + " activity: " + filter.activity.className
2960                                + " priority: " + filter.getPriority());
2961                        }
2962                        // skip setup wizard; allow it to keep the high priority filter
2963                        continue;
2964                    }
2965                    if (DEBUG_FILTERS) {
2966                        Slog.i(TAG, "Protected action; cap priority to 0;"
2967                                + " package: " + filter.activity.info.packageName
2968                                + " activity: " + filter.activity.className
2969                                + " origPrio: " + filter.getPriority());
2970                    }
2971                    filter.setPriority(0);
2972                }
2973            }
2974            mDeferProtectedFilters = false;
2975            mProtectedFilters.clear();
2976
2977            // Now that we know all of the shared libraries, update all clients to have
2978            // the correct library paths.
2979            updateAllSharedLibrariesLPw(null);
2980
2981            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2982                // NOTE: We ignore potential failures here during a system scan (like
2983                // the rest of the commands above) because there's precious little we
2984                // can do about it. A settings error is reported, though.
2985                final List<String> changedAbiCodePath =
2986                        adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2987                if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
2988                    for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
2989                        final String codePathString = changedAbiCodePath.get(i);
2990                        try {
2991                            mInstaller.rmdex(codePathString,
2992                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
2993                        } catch (InstallerException ignored) {
2994                        }
2995                    }
2996                }
2997            }
2998
2999            // Now that we know all the packages we are keeping,
3000            // read and update their last usage times.
3001            mPackageUsage.read(mPackages);
3002            mCompilerStats.read();
3003
3004            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
3005                    SystemClock.uptimeMillis());
3006            Slog.i(TAG, "Time to scan packages: "
3007                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
3008                    + " seconds");
3009
3010            // If the platform SDK has changed since the last time we booted,
3011            // we need to re-grant app permission to catch any new ones that
3012            // appear.  This is really a hack, and means that apps can in some
3013            // cases get permissions that the user didn't initially explicitly
3014            // allow...  it would be nice to have some better way to handle
3015            // this situation.
3016            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
3017            if (sdkUpdated) {
3018                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
3019                        + mSdkVersion + "; regranting permissions for internal storage");
3020            }
3021            mPermissionManager.updateAllPermissions(
3022                    StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(),
3023                    mPermissionCallback);
3024            ver.sdkVersion = mSdkVersion;
3025
3026            // If this is the first boot or an update from pre-M, and it is a normal
3027            // boot, then we need to initialize the default preferred apps across
3028            // all defined users.
3029            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
3030                for (UserInfo user : sUserManager.getUsers(true)) {
3031                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
3032                    applyFactoryDefaultBrowserLPw(user.id);
3033                    primeDomainVerificationsLPw(user.id);
3034                }
3035            }
3036
3037            // Prepare storage for system user really early during boot,
3038            // since core system apps like SettingsProvider and SystemUI
3039            // can't wait for user to start
3040            final int storageFlags;
3041            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
3042                storageFlags = StorageManager.FLAG_STORAGE_DE;
3043            } else {
3044                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
3045            }
3046            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
3047                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
3048                    true /* onlyCoreApps */);
3049            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
3050                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
3051                        Trace.TRACE_TAG_PACKAGE_MANAGER);
3052                traceLog.traceBegin("AppDataFixup");
3053                try {
3054                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
3055                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
3056                } catch (InstallerException e) {
3057                    Slog.w(TAG, "Trouble fixing GIDs", e);
3058                }
3059                traceLog.traceEnd();
3060
3061                traceLog.traceBegin("AppDataPrepare");
3062                if (deferPackages == null || deferPackages.isEmpty()) {
3063                    return;
3064                }
3065                int count = 0;
3066                for (String pkgName : deferPackages) {
3067                    PackageParser.Package pkg = null;
3068                    synchronized (mPackages) {
3069                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
3070                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
3071                            pkg = ps.pkg;
3072                        }
3073                    }
3074                    if (pkg != null) {
3075                        synchronized (mInstallLock) {
3076                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
3077                                    true /* maybeMigrateAppData */);
3078                        }
3079                        count++;
3080                    }
3081                }
3082                traceLog.traceEnd();
3083                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
3084            }, "prepareAppData");
3085
3086            // If this is first boot after an OTA, and a normal boot, then
3087            // we need to clear code cache directories.
3088            // Note that we do *not* clear the application profiles. These remain valid
3089            // across OTAs and are used to drive profile verification (post OTA) and
3090            // profile compilation (without waiting to collect a fresh set of profiles).
3091            if (mIsUpgrade && !onlyCore) {
3092                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
3093                for (int i = 0; i < mSettings.mPackages.size(); i++) {
3094                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
3095                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
3096                        // No apps are running this early, so no need to freeze
3097                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
3098                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3099                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3100                    }
3101                }
3102                ver.fingerprint = Build.FINGERPRINT;
3103            }
3104
3105            checkDefaultBrowser();
3106
3107            // clear only after permissions and other defaults have been updated
3108            mExistingSystemPackages.clear();
3109            mPromoteSystemApps = false;
3110
3111            // All the changes are done during package scanning.
3112            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3113
3114            // can downgrade to reader
3115            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3116            mSettings.writeLPr();
3117            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3118            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3119                    SystemClock.uptimeMillis());
3120
3121            if (!mOnlyCore) {
3122                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3123                mRequiredInstallerPackage = getRequiredInstallerLPr();
3124                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3125                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3126                if (mIntentFilterVerifierComponent != null) {
3127                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3128                            mIntentFilterVerifierComponent);
3129                } else {
3130                    mIntentFilterVerifier = null;
3131                }
3132                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3133                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3134                        SharedLibraryInfo.VERSION_UNDEFINED);
3135                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3136                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3137                        SharedLibraryInfo.VERSION_UNDEFINED);
3138            } else {
3139                mRequiredVerifierPackage = null;
3140                mRequiredInstallerPackage = null;
3141                mRequiredUninstallerPackage = null;
3142                mIntentFilterVerifierComponent = null;
3143                mIntentFilterVerifier = null;
3144                mServicesSystemSharedLibraryPackageName = null;
3145                mSharedSystemSharedLibraryPackageName = null;
3146            }
3147
3148            mInstallerService = new PackageInstallerService(context, this);
3149            final Pair<ComponentName, String> instantAppResolverComponent =
3150                    getInstantAppResolverLPr();
3151            if (instantAppResolverComponent != null) {
3152                if (DEBUG_EPHEMERAL) {
3153                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3154                }
3155                mInstantAppResolverConnection = new EphemeralResolverConnection(
3156                        mContext, instantAppResolverComponent.first,
3157                        instantAppResolverComponent.second);
3158                mInstantAppResolverSettingsComponent =
3159                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3160            } else {
3161                mInstantAppResolverConnection = null;
3162                mInstantAppResolverSettingsComponent = null;
3163            }
3164            updateInstantAppInstallerLocked(null);
3165
3166            // Read and update the usage of dex files.
3167            // Do this at the end of PM init so that all the packages have their
3168            // data directory reconciled.
3169            // At this point we know the code paths of the packages, so we can validate
3170            // the disk file and build the internal cache.
3171            // The usage file is expected to be small so loading and verifying it
3172            // should take a fairly small time compare to the other activities (e.g. package
3173            // scanning).
3174            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3175            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3176            for (int userId : currentUserIds) {
3177                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3178            }
3179            mDexManager.load(userPackages);
3180            if (mIsUpgrade) {
3181                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3182                        (int) (SystemClock.uptimeMillis() - startTime));
3183            }
3184        } // synchronized (mPackages)
3185        } // synchronized (mInstallLock)
3186
3187        // Now after opening every single application zip, make sure they
3188        // are all flushed.  Not really needed, but keeps things nice and
3189        // tidy.
3190        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3191        Runtime.getRuntime().gc();
3192        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3193
3194        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3195        FallbackCategoryProvider.loadFallbacks();
3196        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3197
3198        // The initial scanning above does many calls into installd while
3199        // holding the mPackages lock, but we're mostly interested in yelling
3200        // once we have a booted system.
3201        mInstaller.setWarnIfHeld(mPackages);
3202
3203        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3204    }
3205
3206    /**
3207     * Uncompress and install stub applications.
3208     * <p>In order to save space on the system partition, some applications are shipped in a
3209     * compressed form. In addition the compressed bits for the full application, the
3210     * system image contains a tiny stub comprised of only the Android manifest.
3211     * <p>During the first boot, attempt to uncompress and install the full application. If
3212     * the application can't be installed for any reason, disable the stub and prevent
3213     * uncompressing the full application during future boots.
3214     * <p>In order to forcefully attempt an installation of a full application, go to app
3215     * settings and enable the application.
3216     */
3217    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3218        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3219            final String pkgName = stubSystemApps.get(i);
3220            // skip if the system package is already disabled
3221            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3222                stubSystemApps.remove(i);
3223                continue;
3224            }
3225            // skip if the package isn't installed (?!); this should never happen
3226            final PackageParser.Package pkg = mPackages.get(pkgName);
3227            if (pkg == null) {
3228                stubSystemApps.remove(i);
3229                continue;
3230            }
3231            // skip if the package has been disabled by the user
3232            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3233            if (ps != null) {
3234                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3235                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3236                    stubSystemApps.remove(i);
3237                    continue;
3238                }
3239            }
3240
3241            if (DEBUG_COMPRESSION) {
3242                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3243            }
3244
3245            // uncompress the binary to its eventual destination on /data
3246            final File scanFile = decompressPackage(pkg);
3247            if (scanFile == null) {
3248                continue;
3249            }
3250
3251            // install the package to replace the stub on /system
3252            try {
3253                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3254                removePackageLI(pkg, true /*chatty*/);
3255                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3256                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3257                        UserHandle.USER_SYSTEM, "android");
3258                stubSystemApps.remove(i);
3259                continue;
3260            } catch (PackageManagerException e) {
3261                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3262            }
3263
3264            // any failed attempt to install the package will be cleaned up later
3265        }
3266
3267        // disable any stub still left; these failed to install the full application
3268        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3269            final String pkgName = stubSystemApps.get(i);
3270            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3271            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3272                    UserHandle.USER_SYSTEM, "android");
3273            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3274        }
3275    }
3276
3277    /**
3278     * Decompresses the given package on the system image onto
3279     * the /data partition.
3280     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3281     */
3282    private File decompressPackage(PackageParser.Package pkg) {
3283        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3284        if (compressedFiles == null || compressedFiles.length == 0) {
3285            if (DEBUG_COMPRESSION) {
3286                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3287            }
3288            return null;
3289        }
3290        final File dstCodePath =
3291                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3292        int ret = PackageManager.INSTALL_SUCCEEDED;
3293        try {
3294            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3295            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3296            for (File srcFile : compressedFiles) {
3297                final String srcFileName = srcFile.getName();
3298                final String dstFileName = srcFileName.substring(
3299                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3300                final File dstFile = new File(dstCodePath, dstFileName);
3301                ret = decompressFile(srcFile, dstFile);
3302                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3303                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3304                            + "; pkg: " + pkg.packageName
3305                            + ", file: " + dstFileName);
3306                    break;
3307                }
3308            }
3309        } catch (ErrnoException e) {
3310            logCriticalInfo(Log.ERROR, "Failed to decompress"
3311                    + "; pkg: " + pkg.packageName
3312                    + ", err: " + e.errno);
3313        }
3314        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3315            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3316            NativeLibraryHelper.Handle handle = null;
3317            try {
3318                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3319                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3320                        null /*abiOverride*/);
3321            } catch (IOException e) {
3322                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3323                        + "; pkg: " + pkg.packageName);
3324                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3325            } finally {
3326                IoUtils.closeQuietly(handle);
3327            }
3328        }
3329        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3330            if (dstCodePath == null || !dstCodePath.exists()) {
3331                return null;
3332            }
3333            removeCodePathLI(dstCodePath);
3334            return null;
3335        }
3336
3337        return dstCodePath;
3338    }
3339
3340    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3341        // we're only interested in updating the installer appliction when 1) it's not
3342        // already set or 2) the modified package is the installer
3343        if (mInstantAppInstallerActivity != null
3344                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3345                        .equals(modifiedPackage)) {
3346            return;
3347        }
3348        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3349    }
3350
3351    private static File preparePackageParserCache(boolean isUpgrade) {
3352        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3353            return null;
3354        }
3355
3356        // Disable package parsing on eng builds to allow for faster incremental development.
3357        if (Build.IS_ENG) {
3358            return null;
3359        }
3360
3361        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3362            Slog.i(TAG, "Disabling package parser cache due to system property.");
3363            return null;
3364        }
3365
3366        // The base directory for the package parser cache lives under /data/system/.
3367        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3368                "package_cache");
3369        if (cacheBaseDir == null) {
3370            return null;
3371        }
3372
3373        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3374        // This also serves to "GC" unused entries when the package cache version changes (which
3375        // can only happen during upgrades).
3376        if (isUpgrade) {
3377            FileUtils.deleteContents(cacheBaseDir);
3378        }
3379
3380
3381        // Return the versioned package cache directory. This is something like
3382        // "/data/system/package_cache/1"
3383        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3384
3385        // The following is a workaround to aid development on non-numbered userdebug
3386        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3387        // the system partition is newer.
3388        //
3389        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3390        // that starts with "eng." to signify that this is an engineering build and not
3391        // destined for release.
3392        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3393            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3394
3395            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3396            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3397            // in general and should not be used for production changes. In this specific case,
3398            // we know that they will work.
3399            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3400            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3401                FileUtils.deleteContents(cacheBaseDir);
3402                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3403            }
3404        }
3405
3406        return cacheDir;
3407    }
3408
3409    @Override
3410    public boolean isFirstBoot() {
3411        // allow instant applications
3412        return mFirstBoot;
3413    }
3414
3415    @Override
3416    public boolean isOnlyCoreApps() {
3417        // allow instant applications
3418        return mOnlyCore;
3419    }
3420
3421    @Override
3422    public boolean isUpgrade() {
3423        // allow instant applications
3424        // The system property allows testing ota flow when upgraded to the same image.
3425        return mIsUpgrade || SystemProperties.getBoolean(
3426                "persist.pm.mock-upgrade", false /* default */);
3427    }
3428
3429    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3430        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3431
3432        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3433                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3434                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3435        if (matches.size() == 1) {
3436            return matches.get(0).getComponentInfo().packageName;
3437        } else if (matches.size() == 0) {
3438            Log.e(TAG, "There should probably be a verifier, but, none were found");
3439            return null;
3440        }
3441        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3442    }
3443
3444    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3445        synchronized (mPackages) {
3446            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3447            if (libraryEntry == null) {
3448                throw new IllegalStateException("Missing required shared library:" + name);
3449            }
3450            return libraryEntry.apk;
3451        }
3452    }
3453
3454    private @NonNull String getRequiredInstallerLPr() {
3455        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3456        intent.addCategory(Intent.CATEGORY_DEFAULT);
3457        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3458
3459        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3460                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3461                UserHandle.USER_SYSTEM);
3462        if (matches.size() == 1) {
3463            ResolveInfo resolveInfo = matches.get(0);
3464            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3465                throw new RuntimeException("The installer must be a privileged app");
3466            }
3467            return matches.get(0).getComponentInfo().packageName;
3468        } else {
3469            throw new RuntimeException("There must be exactly one installer; found " + matches);
3470        }
3471    }
3472
3473    private @NonNull String getRequiredUninstallerLPr() {
3474        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3475        intent.addCategory(Intent.CATEGORY_DEFAULT);
3476        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3477
3478        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3479                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3480                UserHandle.USER_SYSTEM);
3481        if (resolveInfo == null ||
3482                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3483            throw new RuntimeException("There must be exactly one uninstaller; found "
3484                    + resolveInfo);
3485        }
3486        return resolveInfo.getComponentInfo().packageName;
3487    }
3488
3489    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3490        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3491
3492        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3493                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3494                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3495        ResolveInfo best = null;
3496        final int N = matches.size();
3497        for (int i = 0; i < N; i++) {
3498            final ResolveInfo cur = matches.get(i);
3499            final String packageName = cur.getComponentInfo().packageName;
3500            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3501                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3502                continue;
3503            }
3504
3505            if (best == null || cur.priority > best.priority) {
3506                best = cur;
3507            }
3508        }
3509
3510        if (best != null) {
3511            return best.getComponentInfo().getComponentName();
3512        }
3513        Slog.w(TAG, "Intent filter verifier not found");
3514        return null;
3515    }
3516
3517    @Override
3518    public @Nullable ComponentName getInstantAppResolverComponent() {
3519        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3520            return null;
3521        }
3522        synchronized (mPackages) {
3523            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3524            if (instantAppResolver == null) {
3525                return null;
3526            }
3527            return instantAppResolver.first;
3528        }
3529    }
3530
3531    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3532        final String[] packageArray =
3533                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3534        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3535            if (DEBUG_EPHEMERAL) {
3536                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3537            }
3538            return null;
3539        }
3540
3541        final int callingUid = Binder.getCallingUid();
3542        final int resolveFlags =
3543                MATCH_DIRECT_BOOT_AWARE
3544                | MATCH_DIRECT_BOOT_UNAWARE
3545                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3546        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3547        final Intent resolverIntent = new Intent(actionName);
3548        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3549                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3550        // temporarily look for the old action
3551        if (resolvers.size() == 0) {
3552            if (DEBUG_EPHEMERAL) {
3553                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3554            }
3555            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3556            resolverIntent.setAction(actionName);
3557            resolvers = queryIntentServicesInternal(resolverIntent, null,
3558                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3559        }
3560        final int N = resolvers.size();
3561        if (N == 0) {
3562            if (DEBUG_EPHEMERAL) {
3563                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3564            }
3565            return null;
3566        }
3567
3568        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3569        for (int i = 0; i < N; i++) {
3570            final ResolveInfo info = resolvers.get(i);
3571
3572            if (info.serviceInfo == null) {
3573                continue;
3574            }
3575
3576            final String packageName = info.serviceInfo.packageName;
3577            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3578                if (DEBUG_EPHEMERAL) {
3579                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3580                            + " pkg: " + packageName + ", info:" + info);
3581                }
3582                continue;
3583            }
3584
3585            if (DEBUG_EPHEMERAL) {
3586                Slog.v(TAG, "Ephemeral resolver found;"
3587                        + " pkg: " + packageName + ", info:" + info);
3588            }
3589            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3590        }
3591        if (DEBUG_EPHEMERAL) {
3592            Slog.v(TAG, "Ephemeral resolver NOT found");
3593        }
3594        return null;
3595    }
3596
3597    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3598        String[] orderedActions = Build.IS_ENG
3599                ? new String[]{
3600                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE + "_TEST",
3601                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE,
3602                        Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE}
3603                : new String[]{
3604                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE,
3605                        Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE};
3606
3607        final int resolveFlags =
3608                MATCH_DIRECT_BOOT_AWARE
3609                        | MATCH_DIRECT_BOOT_UNAWARE
3610                        | Intent.FLAG_IGNORE_EPHEMERAL
3611                        | (!Build.IS_ENG ? MATCH_SYSTEM_ONLY : 0);
3612        final Intent intent = new Intent();
3613        intent.addCategory(Intent.CATEGORY_DEFAULT);
3614        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3615        List<ResolveInfo> matches = null;
3616        for (String action : orderedActions) {
3617            intent.setAction(action);
3618            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3619                    resolveFlags, UserHandle.USER_SYSTEM);
3620            if (matches.isEmpty()) {
3621                if (DEBUG_EPHEMERAL) {
3622                    Slog.d(TAG, "Instant App installer not found with " + action);
3623                }
3624            } else {
3625                break;
3626            }
3627        }
3628        Iterator<ResolveInfo> iter = matches.iterator();
3629        while (iter.hasNext()) {
3630            final ResolveInfo rInfo = iter.next();
3631            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3632            if (ps != null) {
3633                final PermissionsState permissionsState = ps.getPermissionsState();
3634                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)
3635                        || Build.IS_ENG) {
3636                    continue;
3637                }
3638            }
3639            iter.remove();
3640        }
3641        if (matches.size() == 0) {
3642            return null;
3643        } else if (matches.size() == 1) {
3644            return (ActivityInfo) matches.get(0).getComponentInfo();
3645        } else {
3646            throw new RuntimeException(
3647                    "There must be at most one ephemeral installer; found " + matches);
3648        }
3649    }
3650
3651    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3652            @NonNull ComponentName resolver) {
3653        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3654                .addCategory(Intent.CATEGORY_DEFAULT)
3655                .setPackage(resolver.getPackageName());
3656        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3657        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3658                UserHandle.USER_SYSTEM);
3659        // temporarily look for the old action
3660        if (matches.isEmpty()) {
3661            if (DEBUG_EPHEMERAL) {
3662                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3663            }
3664            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3665            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3666                    UserHandle.USER_SYSTEM);
3667        }
3668        if (matches.isEmpty()) {
3669            return null;
3670        }
3671        return matches.get(0).getComponentInfo().getComponentName();
3672    }
3673
3674    private void primeDomainVerificationsLPw(int userId) {
3675        if (DEBUG_DOMAIN_VERIFICATION) {
3676            Slog.d(TAG, "Priming domain verifications in user " + userId);
3677        }
3678
3679        SystemConfig systemConfig = SystemConfig.getInstance();
3680        ArraySet<String> packages = systemConfig.getLinkedApps();
3681
3682        for (String packageName : packages) {
3683            PackageParser.Package pkg = mPackages.get(packageName);
3684            if (pkg != null) {
3685                if (!pkg.isSystem()) {
3686                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3687                    continue;
3688                }
3689
3690                ArraySet<String> domains = null;
3691                for (PackageParser.Activity a : pkg.activities) {
3692                    for (ActivityIntentInfo filter : a.intents) {
3693                        if (hasValidDomains(filter)) {
3694                            if (domains == null) {
3695                                domains = new ArraySet<String>();
3696                            }
3697                            domains.addAll(filter.getHostsList());
3698                        }
3699                    }
3700                }
3701
3702                if (domains != null && domains.size() > 0) {
3703                    if (DEBUG_DOMAIN_VERIFICATION) {
3704                        Slog.v(TAG, "      + " + packageName);
3705                    }
3706                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3707                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3708                    // and then 'always' in the per-user state actually used for intent resolution.
3709                    final IntentFilterVerificationInfo ivi;
3710                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3711                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3712                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3713                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3714                } else {
3715                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3716                            + "' does not handle web links");
3717                }
3718            } else {
3719                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3720            }
3721        }
3722
3723        scheduleWritePackageRestrictionsLocked(userId);
3724        scheduleWriteSettingsLocked();
3725    }
3726
3727    private void applyFactoryDefaultBrowserLPw(int userId) {
3728        // The default browser app's package name is stored in a string resource,
3729        // with a product-specific overlay used for vendor customization.
3730        String browserPkg = mContext.getResources().getString(
3731                com.android.internal.R.string.default_browser);
3732        if (!TextUtils.isEmpty(browserPkg)) {
3733            // non-empty string => required to be a known package
3734            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3735            if (ps == null) {
3736                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3737                browserPkg = null;
3738            } else {
3739                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3740            }
3741        }
3742
3743        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3744        // default.  If there's more than one, just leave everything alone.
3745        if (browserPkg == null) {
3746            calculateDefaultBrowserLPw(userId);
3747        }
3748    }
3749
3750    private void calculateDefaultBrowserLPw(int userId) {
3751        List<String> allBrowsers = resolveAllBrowserApps(userId);
3752        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3753        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3754    }
3755
3756    private List<String> resolveAllBrowserApps(int userId) {
3757        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3758        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3759                PackageManager.MATCH_ALL, userId);
3760
3761        final int count = list.size();
3762        List<String> result = new ArrayList<String>(count);
3763        for (int i=0; i<count; i++) {
3764            ResolveInfo info = list.get(i);
3765            if (info.activityInfo == null
3766                    || !info.handleAllWebDataURI
3767                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3768                    || result.contains(info.activityInfo.packageName)) {
3769                continue;
3770            }
3771            result.add(info.activityInfo.packageName);
3772        }
3773
3774        return result;
3775    }
3776
3777    private boolean packageIsBrowser(String packageName, int userId) {
3778        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3779                PackageManager.MATCH_ALL, userId);
3780        final int N = list.size();
3781        for (int i = 0; i < N; i++) {
3782            ResolveInfo info = list.get(i);
3783            if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) {
3784                return true;
3785            }
3786        }
3787        return false;
3788    }
3789
3790    private void checkDefaultBrowser() {
3791        final int myUserId = UserHandle.myUserId();
3792        final String packageName = getDefaultBrowserPackageName(myUserId);
3793        if (packageName != null) {
3794            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3795            if (info == null) {
3796                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3797                synchronized (mPackages) {
3798                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3799                }
3800            }
3801        }
3802    }
3803
3804    @Override
3805    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3806            throws RemoteException {
3807        try {
3808            return super.onTransact(code, data, reply, flags);
3809        } catch (RuntimeException e) {
3810            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3811                Slog.wtf(TAG, "Package Manager Crash", e);
3812            }
3813            throw e;
3814        }
3815    }
3816
3817    static int[] appendInts(int[] cur, int[] add) {
3818        if (add == null) return cur;
3819        if (cur == null) return add;
3820        final int N = add.length;
3821        for (int i=0; i<N; i++) {
3822            cur = appendInt(cur, add[i]);
3823        }
3824        return cur;
3825    }
3826
3827    /**
3828     * Returns whether or not a full application can see an instant application.
3829     * <p>
3830     * Currently, there are three cases in which this can occur:
3831     * <ol>
3832     * <li>The calling application is a "special" process. Special processes
3833     *     are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li>
3834     * <li>The calling application has the permission
3835     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li>
3836     * <li>The calling application is the default launcher on the
3837     *     system partition.</li>
3838     * </ol>
3839     */
3840    private boolean canViewInstantApps(int callingUid, int userId) {
3841        if (callingUid < Process.FIRST_APPLICATION_UID) {
3842            return true;
3843        }
3844        if (mContext.checkCallingOrSelfPermission(
3845                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3846            return true;
3847        }
3848        if (mContext.checkCallingOrSelfPermission(
3849                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3850            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3851            if (homeComponent != null
3852                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3853                return true;
3854            }
3855        }
3856        return false;
3857    }
3858
3859    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3860        if (!sUserManager.exists(userId)) return null;
3861        if (ps == null) {
3862            return null;
3863        }
3864        PackageParser.Package p = ps.pkg;
3865        if (p == null) {
3866            return null;
3867        }
3868        final int callingUid = Binder.getCallingUid();
3869        // Filter out ephemeral app metadata:
3870        //   * The system/shell/root can see metadata for any app
3871        //   * An installed app can see metadata for 1) other installed apps
3872        //     and 2) ephemeral apps that have explicitly interacted with it
3873        //   * Ephemeral apps can only see their own data and exposed installed apps
3874        //   * Holding a signature permission allows seeing instant apps
3875        if (filterAppAccessLPr(ps, callingUid, userId)) {
3876            return null;
3877        }
3878
3879        final PermissionsState permissionsState = ps.getPermissionsState();
3880
3881        // Compute GIDs only if requested
3882        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3883                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3884        // Compute granted permissions only if package has requested permissions
3885        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3886                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3887        final PackageUserState state = ps.readUserState(userId);
3888
3889        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3890                && ps.isSystem()) {
3891            flags |= MATCH_ANY_USER;
3892        }
3893
3894        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3895                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3896
3897        if (packageInfo == null) {
3898            return null;
3899        }
3900
3901        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3902                resolveExternalPackageNameLPr(p);
3903
3904        return packageInfo;
3905    }
3906
3907    @Override
3908    public void checkPackageStartable(String packageName, int userId) {
3909        final int callingUid = Binder.getCallingUid();
3910        if (getInstantAppPackageName(callingUid) != null) {
3911            throw new SecurityException("Instant applications don't have access to this method");
3912        }
3913        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3914        synchronized (mPackages) {
3915            final PackageSetting ps = mSettings.mPackages.get(packageName);
3916            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3917                throw new SecurityException("Package " + packageName + " was not found!");
3918            }
3919
3920            if (!ps.getInstalled(userId)) {
3921                throw new SecurityException(
3922                        "Package " + packageName + " was not installed for user " + userId + "!");
3923            }
3924
3925            if (mSafeMode && !ps.isSystem()) {
3926                throw new SecurityException("Package " + packageName + " not a system app!");
3927            }
3928
3929            if (mFrozenPackages.contains(packageName)) {
3930                throw new SecurityException("Package " + packageName + " is currently frozen!");
3931            }
3932
3933            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3934                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3935            }
3936        }
3937    }
3938
3939    @Override
3940    public boolean isPackageAvailable(String packageName, int userId) {
3941        if (!sUserManager.exists(userId)) return false;
3942        final int callingUid = Binder.getCallingUid();
3943        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
3944                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3945        synchronized (mPackages) {
3946            PackageParser.Package p = mPackages.get(packageName);
3947            if (p != null) {
3948                final PackageSetting ps = (PackageSetting) p.mExtras;
3949                if (filterAppAccessLPr(ps, callingUid, userId)) {
3950                    return false;
3951                }
3952                if (ps != null) {
3953                    final PackageUserState state = ps.readUserState(userId);
3954                    if (state != null) {
3955                        return PackageParser.isAvailable(state);
3956                    }
3957                }
3958            }
3959        }
3960        return false;
3961    }
3962
3963    @Override
3964    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3965        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3966                flags, Binder.getCallingUid(), userId);
3967    }
3968
3969    @Override
3970    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3971            int flags, int userId) {
3972        return getPackageInfoInternal(versionedPackage.getPackageName(),
3973                versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId);
3974    }
3975
3976    /**
3977     * Important: The provided filterCallingUid is used exclusively to filter out packages
3978     * that can be seen based on user state. It's typically the original caller uid prior
3979     * to clearing. Because it can only be provided by trusted code, it's value can be
3980     * trusted and will be used as-is; unlike userId which will be validated by this method.
3981     */
3982    private PackageInfo getPackageInfoInternal(String packageName, long versionCode,
3983            int flags, int filterCallingUid, int userId) {
3984        if (!sUserManager.exists(userId)) return null;
3985        flags = updateFlagsForPackage(flags, userId, packageName);
3986        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
3987                false /* requireFullPermission */, false /* checkShell */, "get package info");
3988
3989        // reader
3990        synchronized (mPackages) {
3991            // Normalize package name to handle renamed packages and static libs
3992            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3993
3994            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3995            if (matchFactoryOnly) {
3996                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3997                if (ps != null) {
3998                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3999                        return null;
4000                    }
4001                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4002                        return null;
4003                    }
4004                    return generatePackageInfo(ps, flags, userId);
4005                }
4006            }
4007
4008            PackageParser.Package p = mPackages.get(packageName);
4009            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
4010                return null;
4011            }
4012            if (DEBUG_PACKAGE_INFO)
4013                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
4014            if (p != null) {
4015                final PackageSetting ps = (PackageSetting) p.mExtras;
4016                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4017                    return null;
4018                }
4019                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
4020                    return null;
4021                }
4022                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
4023            }
4024            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
4025                final PackageSetting ps = mSettings.mPackages.get(packageName);
4026                if (ps == null) return null;
4027                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4028                    return null;
4029                }
4030                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4031                    return null;
4032                }
4033                return generatePackageInfo(ps, flags, userId);
4034            }
4035        }
4036        return null;
4037    }
4038
4039    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
4040        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
4041            return true;
4042        }
4043        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
4044            return true;
4045        }
4046        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4047            return true;
4048        }
4049        return false;
4050    }
4051
4052    private boolean isComponentVisibleToInstantApp(
4053            @Nullable ComponentName component, @ComponentType int type) {
4054        if (type == TYPE_ACTIVITY) {
4055            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4056            return activity != null
4057                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4058                    : false;
4059        } else if (type == TYPE_RECEIVER) {
4060            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4061            return activity != null
4062                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4063                    : false;
4064        } else if (type == TYPE_SERVICE) {
4065            final PackageParser.Service service = mServices.mServices.get(component);
4066            return service != null
4067                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4068                    : false;
4069        } else if (type == TYPE_PROVIDER) {
4070            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4071            return provider != null
4072                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4073                    : false;
4074        } else if (type == TYPE_UNKNOWN) {
4075            return isComponentVisibleToInstantApp(component);
4076        }
4077        return false;
4078    }
4079
4080    /**
4081     * Returns whether or not access to the application should be filtered.
4082     * <p>
4083     * Access may be limited based upon whether the calling or target applications
4084     * are instant applications.
4085     *
4086     * @see #canAccessInstantApps(int)
4087     */
4088    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4089            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4090        // if we're in an isolated process, get the real calling UID
4091        if (Process.isIsolated(callingUid)) {
4092            callingUid = mIsolatedOwners.get(callingUid);
4093        }
4094        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4095        final boolean callerIsInstantApp = instantAppPkgName != null;
4096        if (ps == null) {
4097            if (callerIsInstantApp) {
4098                // pretend the application exists, but, needs to be filtered
4099                return true;
4100            }
4101            return false;
4102        }
4103        // if the target and caller are the same application, don't filter
4104        if (isCallerSameApp(ps.name, callingUid)) {
4105            return false;
4106        }
4107        if (callerIsInstantApp) {
4108            // request for a specific component; if it hasn't been explicitly exposed, filter
4109            if (component != null) {
4110                return !isComponentVisibleToInstantApp(component, componentType);
4111            }
4112            // request for application; if no components have been explicitly exposed, filter
4113            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4114        }
4115        if (ps.getInstantApp(userId)) {
4116            // caller can see all components of all instant applications, don't filter
4117            if (canViewInstantApps(callingUid, userId)) {
4118                return false;
4119            }
4120            // request for a specific instant application component, filter
4121            if (component != null) {
4122                return true;
4123            }
4124            // request for an instant application; if the caller hasn't been granted access, filter
4125            return !mInstantAppRegistry.isInstantAccessGranted(
4126                    userId, UserHandle.getAppId(callingUid), ps.appId);
4127        }
4128        return false;
4129    }
4130
4131    /**
4132     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4133     */
4134    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4135        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4136    }
4137
4138    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4139            int flags) {
4140        // Callers can access only the libs they depend on, otherwise they need to explicitly
4141        // ask for the shared libraries given the caller is allowed to access all static libs.
4142        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4143            // System/shell/root get to see all static libs
4144            final int appId = UserHandle.getAppId(uid);
4145            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4146                    || appId == Process.ROOT_UID) {
4147                return false;
4148            }
4149        }
4150
4151        // No package means no static lib as it is always on internal storage
4152        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4153            return false;
4154        }
4155
4156        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4157                ps.pkg.staticSharedLibVersion);
4158        if (libEntry == null) {
4159            return false;
4160        }
4161
4162        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4163        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4164        if (uidPackageNames == null) {
4165            return true;
4166        }
4167
4168        for (String uidPackageName : uidPackageNames) {
4169            if (ps.name.equals(uidPackageName)) {
4170                return false;
4171            }
4172            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4173            if (uidPs != null) {
4174                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4175                        libEntry.info.getName());
4176                if (index < 0) {
4177                    continue;
4178                }
4179                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) {
4180                    return false;
4181                }
4182            }
4183        }
4184        return true;
4185    }
4186
4187    @Override
4188    public String[] currentToCanonicalPackageNames(String[] names) {
4189        final int callingUid = Binder.getCallingUid();
4190        if (getInstantAppPackageName(callingUid) != null) {
4191            return names;
4192        }
4193        final String[] out = new String[names.length];
4194        // reader
4195        synchronized (mPackages) {
4196            final int callingUserId = UserHandle.getUserId(callingUid);
4197            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4198            for (int i=names.length-1; i>=0; i--) {
4199                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4200                boolean translateName = false;
4201                if (ps != null && ps.realName != null) {
4202                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4203                    translateName = !targetIsInstantApp
4204                            || canViewInstantApps
4205                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4206                                    UserHandle.getAppId(callingUid), ps.appId);
4207                }
4208                out[i] = translateName ? ps.realName : names[i];
4209            }
4210        }
4211        return out;
4212    }
4213
4214    @Override
4215    public String[] canonicalToCurrentPackageNames(String[] names) {
4216        final int callingUid = Binder.getCallingUid();
4217        if (getInstantAppPackageName(callingUid) != null) {
4218            return names;
4219        }
4220        final String[] out = new String[names.length];
4221        // reader
4222        synchronized (mPackages) {
4223            final int callingUserId = UserHandle.getUserId(callingUid);
4224            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4225            for (int i=names.length-1; i>=0; i--) {
4226                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4227                boolean translateName = false;
4228                if (cur != null) {
4229                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4230                    final boolean targetIsInstantApp =
4231                            ps != null && ps.getInstantApp(callingUserId);
4232                    translateName = !targetIsInstantApp
4233                            || canViewInstantApps
4234                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4235                                    UserHandle.getAppId(callingUid), ps.appId);
4236                }
4237                out[i] = translateName ? cur : names[i];
4238            }
4239        }
4240        return out;
4241    }
4242
4243    @Override
4244    public int getPackageUid(String packageName, int flags, int userId) {
4245        if (!sUserManager.exists(userId)) return -1;
4246        final int callingUid = Binder.getCallingUid();
4247        flags = updateFlagsForPackage(flags, userId, packageName);
4248        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4249                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4250
4251        // reader
4252        synchronized (mPackages) {
4253            final PackageParser.Package p = mPackages.get(packageName);
4254            if (p != null && p.isMatch(flags)) {
4255                PackageSetting ps = (PackageSetting) p.mExtras;
4256                if (filterAppAccessLPr(ps, callingUid, userId)) {
4257                    return -1;
4258                }
4259                return UserHandle.getUid(userId, p.applicationInfo.uid);
4260            }
4261            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4262                final PackageSetting ps = mSettings.mPackages.get(packageName);
4263                if (ps != null && ps.isMatch(flags)
4264                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4265                    return UserHandle.getUid(userId, ps.appId);
4266                }
4267            }
4268        }
4269
4270        return -1;
4271    }
4272
4273    @Override
4274    public int[] getPackageGids(String packageName, int flags, int userId) {
4275        if (!sUserManager.exists(userId)) return null;
4276        final int callingUid = Binder.getCallingUid();
4277        flags = updateFlagsForPackage(flags, userId, packageName);
4278        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4279                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4280
4281        // reader
4282        synchronized (mPackages) {
4283            final PackageParser.Package p = mPackages.get(packageName);
4284            if (p != null && p.isMatch(flags)) {
4285                PackageSetting ps = (PackageSetting) p.mExtras;
4286                if (filterAppAccessLPr(ps, callingUid, userId)) {
4287                    return null;
4288                }
4289                // TODO: Shouldn't this be checking for package installed state for userId and
4290                // return null?
4291                return ps.getPermissionsState().computeGids(userId);
4292            }
4293            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4294                final PackageSetting ps = mSettings.mPackages.get(packageName);
4295                if (ps != null && ps.isMatch(flags)
4296                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4297                    return ps.getPermissionsState().computeGids(userId);
4298                }
4299            }
4300        }
4301
4302        return null;
4303    }
4304
4305    @Override
4306    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4307        return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4308    }
4309
4310    @Override
4311    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4312            int flags) {
4313        final List<PermissionInfo> permissionList =
4314                mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid());
4315        return (permissionList == null) ? null : new ParceledListSlice<>(permissionList);
4316    }
4317
4318    @Override
4319    public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) {
4320        return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid());
4321    }
4322
4323    @Override
4324    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4325        final List<PermissionGroupInfo> permissionList =
4326                mPermissionManager.getAllPermissionGroups(flags, getCallingUid());
4327        return (permissionList == null)
4328                ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList);
4329    }
4330
4331    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4332            int filterCallingUid, int userId) {
4333        if (!sUserManager.exists(userId)) return null;
4334        PackageSetting ps = mSettings.mPackages.get(packageName);
4335        if (ps != null) {
4336            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4337                return null;
4338            }
4339            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4340                return null;
4341            }
4342            if (ps.pkg == null) {
4343                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4344                if (pInfo != null) {
4345                    return pInfo.applicationInfo;
4346                }
4347                return null;
4348            }
4349            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4350                    ps.readUserState(userId), userId);
4351            if (ai != null) {
4352                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4353            }
4354            return ai;
4355        }
4356        return null;
4357    }
4358
4359    @Override
4360    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4361        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4362    }
4363
4364    /**
4365     * Important: The provided filterCallingUid is used exclusively to filter out applications
4366     * that can be seen based on user state. It's typically the original caller uid prior
4367     * to clearing. Because it can only be provided by trusted code, it's value can be
4368     * trusted and will be used as-is; unlike userId which will be validated by this method.
4369     */
4370    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4371            int filterCallingUid, int userId) {
4372        if (!sUserManager.exists(userId)) return null;
4373        flags = updateFlagsForApplication(flags, userId, packageName);
4374        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4375                false /* requireFullPermission */, false /* checkShell */, "get application info");
4376
4377        // writer
4378        synchronized (mPackages) {
4379            // Normalize package name to handle renamed packages and static libs
4380            packageName = resolveInternalPackageNameLPr(packageName,
4381                    PackageManager.VERSION_CODE_HIGHEST);
4382
4383            PackageParser.Package p = mPackages.get(packageName);
4384            if (DEBUG_PACKAGE_INFO) Log.v(
4385                    TAG, "getApplicationInfo " + packageName
4386                    + ": " + p);
4387            if (p != null) {
4388                PackageSetting ps = mSettings.mPackages.get(packageName);
4389                if (ps == null) return null;
4390                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4391                    return null;
4392                }
4393                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4394                    return null;
4395                }
4396                // Note: isEnabledLP() does not apply here - always return info
4397                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4398                        p, flags, ps.readUserState(userId), userId);
4399                if (ai != null) {
4400                    ai.packageName = resolveExternalPackageNameLPr(p);
4401                }
4402                return ai;
4403            }
4404            if ("android".equals(packageName)||"system".equals(packageName)) {
4405                return mAndroidApplication;
4406            }
4407            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4408                // Already generates the external package name
4409                return generateApplicationInfoFromSettingsLPw(packageName,
4410                        flags, filterCallingUid, userId);
4411            }
4412        }
4413        return null;
4414    }
4415
4416    private String normalizePackageNameLPr(String packageName) {
4417        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4418        return normalizedPackageName != null ? normalizedPackageName : packageName;
4419    }
4420
4421    @Override
4422    public void deletePreloadsFileCache() {
4423        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4424            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4425        }
4426        File dir = Environment.getDataPreloadsFileCacheDirectory();
4427        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4428        FileUtils.deleteContents(dir);
4429    }
4430
4431    @Override
4432    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4433            final int storageFlags, final IPackageDataObserver observer) {
4434        mContext.enforceCallingOrSelfPermission(
4435                android.Manifest.permission.CLEAR_APP_CACHE, null);
4436        mHandler.post(() -> {
4437            boolean success = false;
4438            try {
4439                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4440                success = true;
4441            } catch (IOException e) {
4442                Slog.w(TAG, e);
4443            }
4444            if (observer != null) {
4445                try {
4446                    observer.onRemoveCompleted(null, success);
4447                } catch (RemoteException e) {
4448                    Slog.w(TAG, e);
4449                }
4450            }
4451        });
4452    }
4453
4454    @Override
4455    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4456            final int storageFlags, final IntentSender pi) {
4457        mContext.enforceCallingOrSelfPermission(
4458                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4459        mHandler.post(() -> {
4460            boolean success = false;
4461            try {
4462                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4463                success = true;
4464            } catch (IOException e) {
4465                Slog.w(TAG, e);
4466            }
4467            if (pi != null) {
4468                try {
4469                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4470                } catch (SendIntentException e) {
4471                    Slog.w(TAG, e);
4472                }
4473            }
4474        });
4475    }
4476
4477    /**
4478     * Blocking call to clear various types of cached data across the system
4479     * until the requested bytes are available.
4480     */
4481    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4482        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4483        final File file = storage.findPathForUuid(volumeUuid);
4484        if (file.getUsableSpace() >= bytes) return;
4485
4486        if (ENABLE_FREE_CACHE_V2) {
4487            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4488                    volumeUuid);
4489            final boolean aggressive = (storageFlags
4490                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4491            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4492
4493            // 1. Pre-flight to determine if we have any chance to succeed
4494            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4495            if (internalVolume && (aggressive || SystemProperties
4496                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4497                deletePreloadsFileCache();
4498                if (file.getUsableSpace() >= bytes) return;
4499            }
4500
4501            // 3. Consider parsed APK data (aggressive only)
4502            if (internalVolume && aggressive) {
4503                FileUtils.deleteContents(mCacheDir);
4504                if (file.getUsableSpace() >= bytes) return;
4505            }
4506
4507            // 4. Consider cached app data (above quotas)
4508            try {
4509                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4510                        Installer.FLAG_FREE_CACHE_V2);
4511            } catch (InstallerException ignored) {
4512            }
4513            if (file.getUsableSpace() >= bytes) return;
4514
4515            // 5. Consider shared libraries with refcount=0 and age>min cache period
4516            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4517                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4518                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4519                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4520                return;
4521            }
4522
4523            // 6. Consider dexopt output (aggressive only)
4524            // TODO: Implement
4525
4526            // 7. Consider installed instant apps unused longer than min cache period
4527            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4528                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4529                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4530                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4531                return;
4532            }
4533
4534            // 8. Consider cached app data (below quotas)
4535            try {
4536                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4537                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4538            } catch (InstallerException ignored) {
4539            }
4540            if (file.getUsableSpace() >= bytes) return;
4541
4542            // 9. Consider DropBox entries
4543            // TODO: Implement
4544
4545            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4546            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4547                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4548                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4549                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4550                return;
4551            }
4552        } else {
4553            try {
4554                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4555            } catch (InstallerException ignored) {
4556            }
4557            if (file.getUsableSpace() >= bytes) return;
4558        }
4559
4560        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4561    }
4562
4563    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4564            throws IOException {
4565        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4566        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4567
4568        List<VersionedPackage> packagesToDelete = null;
4569        final long now = System.currentTimeMillis();
4570
4571        synchronized (mPackages) {
4572            final int[] allUsers = sUserManager.getUserIds();
4573            final int libCount = mSharedLibraries.size();
4574            for (int i = 0; i < libCount; i++) {
4575                final LongSparseArray<SharedLibraryEntry> versionedLib
4576                        = mSharedLibraries.valueAt(i);
4577                if (versionedLib == null) {
4578                    continue;
4579                }
4580                final int versionCount = versionedLib.size();
4581                for (int j = 0; j < versionCount; j++) {
4582                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4583                    // Skip packages that are not static shared libs.
4584                    if (!libInfo.isStatic()) {
4585                        break;
4586                    }
4587                    // Important: We skip static shared libs used for some user since
4588                    // in such a case we need to keep the APK on the device. The check for
4589                    // a lib being used for any user is performed by the uninstall call.
4590                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4591                    // Resolve the package name - we use synthetic package names internally
4592                    final String internalPackageName = resolveInternalPackageNameLPr(
4593                            declaringPackage.getPackageName(),
4594                            declaringPackage.getLongVersionCode());
4595                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4596                    // Skip unused static shared libs cached less than the min period
4597                    // to prevent pruning a lib needed by a subsequently installed package.
4598                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4599                        continue;
4600                    }
4601                    if (packagesToDelete == null) {
4602                        packagesToDelete = new ArrayList<>();
4603                    }
4604                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4605                            declaringPackage.getLongVersionCode()));
4606                }
4607            }
4608        }
4609
4610        if (packagesToDelete != null) {
4611            final int packageCount = packagesToDelete.size();
4612            for (int i = 0; i < packageCount; i++) {
4613                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4614                // Delete the package synchronously (will fail of the lib used for any user).
4615                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(),
4616                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4617                                == PackageManager.DELETE_SUCCEEDED) {
4618                    if (volume.getUsableSpace() >= neededSpace) {
4619                        return true;
4620                    }
4621                }
4622            }
4623        }
4624
4625        return false;
4626    }
4627
4628    /**
4629     * Update given flags based on encryption status of current user.
4630     */
4631    private int updateFlags(int flags, int userId) {
4632        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4633                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4634            // Caller expressed an explicit opinion about what encryption
4635            // aware/unaware components they want to see, so fall through and
4636            // give them what they want
4637        } else {
4638            // Caller expressed no opinion, so match based on user state
4639            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4640                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4641            } else {
4642                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4643            }
4644        }
4645        return flags;
4646    }
4647
4648    private UserManagerInternal getUserManagerInternal() {
4649        if (mUserManagerInternal == null) {
4650            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4651        }
4652        return mUserManagerInternal;
4653    }
4654
4655    private ActivityManagerInternal getActivityManagerInternal() {
4656        if (mActivityManagerInternal == null) {
4657            mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
4658        }
4659        return mActivityManagerInternal;
4660    }
4661
4662
4663    private DeviceIdleController.LocalService getDeviceIdleController() {
4664        if (mDeviceIdleController == null) {
4665            mDeviceIdleController =
4666                    LocalServices.getService(DeviceIdleController.LocalService.class);
4667        }
4668        return mDeviceIdleController;
4669    }
4670
4671    /**
4672     * Update given flags when being used to request {@link PackageInfo}.
4673     */
4674    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4675        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4676        boolean triaged = true;
4677        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4678                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4679            // Caller is asking for component details, so they'd better be
4680            // asking for specific encryption matching behavior, or be triaged
4681            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4682                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4683                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4684                triaged = false;
4685            }
4686        }
4687        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4688                | PackageManager.MATCH_SYSTEM_ONLY
4689                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4690            triaged = false;
4691        }
4692        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4693            mPermissionManager.enforceCrossUserPermission(
4694                    Binder.getCallingUid(), userId, false, false,
4695                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4696                    + Debug.getCallers(5));
4697        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4698                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4699            // If the caller wants all packages and has a restricted profile associated with it,
4700            // then match all users. This is to make sure that launchers that need to access work
4701            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4702            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4703            flags |= PackageManager.MATCH_ANY_USER;
4704        }
4705        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4706            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4707                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4708        }
4709        return updateFlags(flags, userId);
4710    }
4711
4712    /**
4713     * Update given flags when being used to request {@link ApplicationInfo}.
4714     */
4715    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4716        return updateFlagsForPackage(flags, userId, cookie);
4717    }
4718
4719    /**
4720     * Update given flags when being used to request {@link ComponentInfo}.
4721     */
4722    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4723        if (cookie instanceof Intent) {
4724            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4725                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4726            }
4727        }
4728
4729        boolean triaged = true;
4730        // Caller is asking for component details, so they'd better be
4731        // asking for specific encryption matching behavior, or be triaged
4732        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4733                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4734                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4735            triaged = false;
4736        }
4737        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4738            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4739                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4740        }
4741
4742        return updateFlags(flags, userId);
4743    }
4744
4745    /**
4746     * Update given intent when being used to request {@link ResolveInfo}.
4747     */
4748    private Intent updateIntentForResolve(Intent intent) {
4749        if (intent.getSelector() != null) {
4750            intent = intent.getSelector();
4751        }
4752        if (DEBUG_PREFERRED) {
4753            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4754        }
4755        return intent;
4756    }
4757
4758    /**
4759     * Update given flags when being used to request {@link ResolveInfo}.
4760     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4761     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4762     * flag set. However, this flag is only honoured in three circumstances:
4763     * <ul>
4764     * <li>when called from a system process</li>
4765     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4766     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4767     * action and a {@code android.intent.category.BROWSABLE} category</li>
4768     * </ul>
4769     */
4770    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4771        return updateFlagsForResolve(flags, userId, intent, callingUid,
4772                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4773    }
4774    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4775            boolean wantInstantApps) {
4776        return updateFlagsForResolve(flags, userId, intent, callingUid,
4777                wantInstantApps, false /*onlyExposedExplicitly*/);
4778    }
4779    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4780            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4781        // Safe mode means we shouldn't match any third-party components
4782        if (mSafeMode) {
4783            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4784        }
4785        if (getInstantAppPackageName(callingUid) != null) {
4786            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4787            if (onlyExposedExplicitly) {
4788                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4789            }
4790            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4791            flags |= PackageManager.MATCH_INSTANT;
4792        } else {
4793            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4794            final boolean allowMatchInstant = wantInstantApps
4795                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4796            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4797                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4798            if (!allowMatchInstant) {
4799                flags &= ~PackageManager.MATCH_INSTANT;
4800            }
4801        }
4802        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4803    }
4804
4805    @Override
4806    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4807        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4808    }
4809
4810    /**
4811     * Important: The provided filterCallingUid is used exclusively to filter out activities
4812     * that can be seen based on user state. It's typically the original caller uid prior
4813     * to clearing. Because it can only be provided by trusted code, it's value can be
4814     * trusted and will be used as-is; unlike userId which will be validated by this method.
4815     */
4816    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4817            int filterCallingUid, int userId) {
4818        if (!sUserManager.exists(userId)) return null;
4819        flags = updateFlagsForComponent(flags, userId, component);
4820
4821        if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) {
4822            mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4823                    false /* requireFullPermission */, false /* checkShell */, "get activity info");
4824        }
4825
4826        synchronized (mPackages) {
4827            PackageParser.Activity a = mActivities.mActivities.get(component);
4828
4829            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4830            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4831                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4832                if (ps == null) return null;
4833                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4834                    return null;
4835                }
4836                return PackageParser.generateActivityInfo(
4837                        a, flags, ps.readUserState(userId), userId);
4838            }
4839            if (mResolveComponentName.equals(component)) {
4840                return PackageParser.generateActivityInfo(
4841                        mResolveActivity, flags, new PackageUserState(), userId);
4842            }
4843        }
4844        return null;
4845    }
4846
4847    private boolean isRecentsAccessingChildProfiles(int callingUid, int targetUserId) {
4848        if (!getActivityManagerInternal().isCallerRecents(callingUid)) {
4849            return false;
4850        }
4851        final long token = Binder.clearCallingIdentity();
4852        try {
4853            final int callingUserId = UserHandle.getUserId(callingUid);
4854            if (ActivityManager.getCurrentUser() != callingUserId) {
4855                return false;
4856            }
4857            return sUserManager.isSameProfileGroup(callingUserId, targetUserId);
4858        } finally {
4859            Binder.restoreCallingIdentity(token);
4860        }
4861    }
4862
4863    @Override
4864    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4865            String resolvedType) {
4866        synchronized (mPackages) {
4867            if (component.equals(mResolveComponentName)) {
4868                // The resolver supports EVERYTHING!
4869                return true;
4870            }
4871            final int callingUid = Binder.getCallingUid();
4872            final int callingUserId = UserHandle.getUserId(callingUid);
4873            PackageParser.Activity a = mActivities.mActivities.get(component);
4874            if (a == null) {
4875                return false;
4876            }
4877            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4878            if (ps == null) {
4879                return false;
4880            }
4881            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4882                return false;
4883            }
4884            for (int i=0; i<a.intents.size(); i++) {
4885                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4886                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4887                    return true;
4888                }
4889            }
4890            return false;
4891        }
4892    }
4893
4894    @Override
4895    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4896        if (!sUserManager.exists(userId)) return null;
4897        final int callingUid = Binder.getCallingUid();
4898        flags = updateFlagsForComponent(flags, userId, component);
4899        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4900                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4901        synchronized (mPackages) {
4902            PackageParser.Activity a = mReceivers.mActivities.get(component);
4903            if (DEBUG_PACKAGE_INFO) Log.v(
4904                TAG, "getReceiverInfo " + component + ": " + a);
4905            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4906                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4907                if (ps == null) return null;
4908                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4909                    return null;
4910                }
4911                return PackageParser.generateActivityInfo(
4912                        a, flags, ps.readUserState(userId), userId);
4913            }
4914        }
4915        return null;
4916    }
4917
4918    @Override
4919    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4920            int flags, int userId) {
4921        if (!sUserManager.exists(userId)) return null;
4922        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4923        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4924            return null;
4925        }
4926
4927        flags = updateFlagsForPackage(flags, userId, null);
4928
4929        final boolean canSeeStaticLibraries =
4930                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4931                        == PERMISSION_GRANTED
4932                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4933                        == PERMISSION_GRANTED
4934                || canRequestPackageInstallsInternal(packageName,
4935                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4936                        false  /* throwIfPermNotDeclared*/)
4937                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4938                        == PERMISSION_GRANTED;
4939
4940        synchronized (mPackages) {
4941            List<SharedLibraryInfo> result = null;
4942
4943            final int libCount = mSharedLibraries.size();
4944            for (int i = 0; i < libCount; i++) {
4945                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4946                if (versionedLib == null) {
4947                    continue;
4948                }
4949
4950                final int versionCount = versionedLib.size();
4951                for (int j = 0; j < versionCount; j++) {
4952                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4953                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4954                        break;
4955                    }
4956                    final long identity = Binder.clearCallingIdentity();
4957                    try {
4958                        PackageInfo packageInfo = getPackageInfoVersioned(
4959                                libInfo.getDeclaringPackage(), flags
4960                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4961                        if (packageInfo == null) {
4962                            continue;
4963                        }
4964                    } finally {
4965                        Binder.restoreCallingIdentity(identity);
4966                    }
4967
4968                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4969                            libInfo.getLongVersion(), libInfo.getType(),
4970                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4971                            flags, userId));
4972
4973                    if (result == null) {
4974                        result = new ArrayList<>();
4975                    }
4976                    result.add(resLibInfo);
4977                }
4978            }
4979
4980            return result != null ? new ParceledListSlice<>(result) : null;
4981        }
4982    }
4983
4984    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4985            SharedLibraryInfo libInfo, int flags, int userId) {
4986        List<VersionedPackage> versionedPackages = null;
4987        final int packageCount = mSettings.mPackages.size();
4988        for (int i = 0; i < packageCount; i++) {
4989            PackageSetting ps = mSettings.mPackages.valueAt(i);
4990
4991            if (ps == null) {
4992                continue;
4993            }
4994
4995            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4996                continue;
4997            }
4998
4999            final String libName = libInfo.getName();
5000            if (libInfo.isStatic()) {
5001                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
5002                if (libIdx < 0) {
5003                    continue;
5004                }
5005                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) {
5006                    continue;
5007                }
5008                if (versionedPackages == null) {
5009                    versionedPackages = new ArrayList<>();
5010                }
5011                // If the dependent is a static shared lib, use the public package name
5012                String dependentPackageName = ps.name;
5013                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5014                    dependentPackageName = ps.pkg.manifestPackageName;
5015                }
5016                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5017            } else if (ps.pkg != null) {
5018                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5019                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5020                    if (versionedPackages == null) {
5021                        versionedPackages = new ArrayList<>();
5022                    }
5023                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5024                }
5025            }
5026        }
5027
5028        return versionedPackages;
5029    }
5030
5031    @Override
5032    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5033        if (!sUserManager.exists(userId)) return null;
5034        final int callingUid = Binder.getCallingUid();
5035        flags = updateFlagsForComponent(flags, userId, component);
5036        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5037                false /* requireFullPermission */, false /* checkShell */, "get service info");
5038        synchronized (mPackages) {
5039            PackageParser.Service s = mServices.mServices.get(component);
5040            if (DEBUG_PACKAGE_INFO) Log.v(
5041                TAG, "getServiceInfo " + component + ": " + s);
5042            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5043                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5044                if (ps == null) return null;
5045                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5046                    return null;
5047                }
5048                return PackageParser.generateServiceInfo(
5049                        s, flags, ps.readUserState(userId), userId);
5050            }
5051        }
5052        return null;
5053    }
5054
5055    @Override
5056    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5057        if (!sUserManager.exists(userId)) return null;
5058        final int callingUid = Binder.getCallingUid();
5059        flags = updateFlagsForComponent(flags, userId, component);
5060        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5061                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5062        synchronized (mPackages) {
5063            PackageParser.Provider p = mProviders.mProviders.get(component);
5064            if (DEBUG_PACKAGE_INFO) Log.v(
5065                TAG, "getProviderInfo " + component + ": " + p);
5066            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5067                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5068                if (ps == null) return null;
5069                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5070                    return null;
5071                }
5072                return PackageParser.generateProviderInfo(
5073                        p, flags, ps.readUserState(userId), userId);
5074            }
5075        }
5076        return null;
5077    }
5078
5079    @Override
5080    public String[] getSystemSharedLibraryNames() {
5081        // allow instant applications
5082        synchronized (mPackages) {
5083            Set<String> libs = null;
5084            final int libCount = mSharedLibraries.size();
5085            for (int i = 0; i < libCount; i++) {
5086                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5087                if (versionedLib == null) {
5088                    continue;
5089                }
5090                final int versionCount = versionedLib.size();
5091                for (int j = 0; j < versionCount; j++) {
5092                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5093                    if (!libEntry.info.isStatic()) {
5094                        if (libs == null) {
5095                            libs = new ArraySet<>();
5096                        }
5097                        libs.add(libEntry.info.getName());
5098                        break;
5099                    }
5100                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5101                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5102                            UserHandle.getUserId(Binder.getCallingUid()),
5103                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5104                        if (libs == null) {
5105                            libs = new ArraySet<>();
5106                        }
5107                        libs.add(libEntry.info.getName());
5108                        break;
5109                    }
5110                }
5111            }
5112
5113            if (libs != null) {
5114                String[] libsArray = new String[libs.size()];
5115                libs.toArray(libsArray);
5116                return libsArray;
5117            }
5118
5119            return null;
5120        }
5121    }
5122
5123    @Override
5124    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5125        // allow instant applications
5126        synchronized (mPackages) {
5127            return mServicesSystemSharedLibraryPackageName;
5128        }
5129    }
5130
5131    @Override
5132    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5133        // allow instant applications
5134        synchronized (mPackages) {
5135            return mSharedSystemSharedLibraryPackageName;
5136        }
5137    }
5138
5139    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5140        for (int i = userList.length - 1; i >= 0; --i) {
5141            final int userId = userList[i];
5142            // don't add instant app to the list of updates
5143            if (pkgSetting.getInstantApp(userId)) {
5144                continue;
5145            }
5146            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5147            if (changedPackages == null) {
5148                changedPackages = new SparseArray<>();
5149                mChangedPackages.put(userId, changedPackages);
5150            }
5151            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5152            if (sequenceNumbers == null) {
5153                sequenceNumbers = new HashMap<>();
5154                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5155            }
5156            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5157            if (sequenceNumber != null) {
5158                changedPackages.remove(sequenceNumber);
5159            }
5160            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5161            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5162        }
5163        mChangedPackagesSequenceNumber++;
5164    }
5165
5166    @Override
5167    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5168        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5169            return null;
5170        }
5171        synchronized (mPackages) {
5172            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5173                return null;
5174            }
5175            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5176            if (changedPackages == null) {
5177                return null;
5178            }
5179            final List<String> packageNames =
5180                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5181            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5182                final String packageName = changedPackages.get(i);
5183                if (packageName != null) {
5184                    packageNames.add(packageName);
5185                }
5186            }
5187            return packageNames.isEmpty()
5188                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5189        }
5190    }
5191
5192    @Override
5193    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5194        // allow instant applications
5195        ArrayList<FeatureInfo> res;
5196        synchronized (mAvailableFeatures) {
5197            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5198            res.addAll(mAvailableFeatures.values());
5199        }
5200        final FeatureInfo fi = new FeatureInfo();
5201        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5202                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5203        res.add(fi);
5204
5205        return new ParceledListSlice<>(res);
5206    }
5207
5208    @Override
5209    public boolean hasSystemFeature(String name, int version) {
5210        // allow instant applications
5211        synchronized (mAvailableFeatures) {
5212            final FeatureInfo feat = mAvailableFeatures.get(name);
5213            if (feat == null) {
5214                return false;
5215            } else {
5216                return feat.version >= version;
5217            }
5218        }
5219    }
5220
5221    @Override
5222    public int checkPermission(String permName, String pkgName, int userId) {
5223        return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
5224    }
5225
5226    @Override
5227    public int checkUidPermission(String permName, int uid) {
5228        return mPermissionManager.checkUidPermission(permName, uid, getCallingUid());
5229    }
5230
5231    @Override
5232    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5233        if (UserHandle.getCallingUserId() != userId) {
5234            mContext.enforceCallingPermission(
5235                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5236                    "isPermissionRevokedByPolicy for user " + userId);
5237        }
5238
5239        if (checkPermission(permission, packageName, userId)
5240                == PackageManager.PERMISSION_GRANTED) {
5241            return false;
5242        }
5243
5244        final int callingUid = Binder.getCallingUid();
5245        if (getInstantAppPackageName(callingUid) != null) {
5246            if (!isCallerSameApp(packageName, callingUid)) {
5247                return false;
5248            }
5249        } else {
5250            if (isInstantApp(packageName, userId)) {
5251                return false;
5252            }
5253        }
5254
5255        final long identity = Binder.clearCallingIdentity();
5256        try {
5257            final int flags = getPermissionFlags(permission, packageName, userId);
5258            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5259        } finally {
5260            Binder.restoreCallingIdentity(identity);
5261        }
5262    }
5263
5264    @Override
5265    public String getPermissionControllerPackageName() {
5266        synchronized (mPackages) {
5267            return mRequiredInstallerPackage;
5268        }
5269    }
5270
5271    private boolean addDynamicPermission(PermissionInfo info, final boolean async) {
5272        return mPermissionManager.addDynamicPermission(
5273                info, async, getCallingUid(), new PermissionCallback() {
5274                    @Override
5275                    public void onPermissionChanged() {
5276                        if (!async) {
5277                            mSettings.writeLPr();
5278                        } else {
5279                            scheduleWriteSettingsLocked();
5280                        }
5281                    }
5282                });
5283    }
5284
5285    @Override
5286    public boolean addPermission(PermissionInfo info) {
5287        synchronized (mPackages) {
5288            return addDynamicPermission(info, false);
5289        }
5290    }
5291
5292    @Override
5293    public boolean addPermissionAsync(PermissionInfo info) {
5294        synchronized (mPackages) {
5295            return addDynamicPermission(info, true);
5296        }
5297    }
5298
5299    @Override
5300    public void removePermission(String permName) {
5301        mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback);
5302    }
5303
5304    @Override
5305    public void grantRuntimePermission(String packageName, String permName, final int userId) {
5306        mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
5307                getCallingUid(), userId, mPermissionCallback);
5308    }
5309
5310    @Override
5311    public void revokeRuntimePermission(String packageName, String permName, int userId) {
5312        mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
5313                getCallingUid(), userId, mPermissionCallback);
5314    }
5315
5316    @Override
5317    public void resetRuntimePermissions() {
5318        mContext.enforceCallingOrSelfPermission(
5319                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5320                "revokeRuntimePermission");
5321
5322        int callingUid = Binder.getCallingUid();
5323        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5324            mContext.enforceCallingOrSelfPermission(
5325                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5326                    "resetRuntimePermissions");
5327        }
5328
5329        synchronized (mPackages) {
5330            mPermissionManager.updateAllPermissions(
5331                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
5332                    mPermissionCallback);
5333            for (int userId : UserManagerService.getInstance().getUserIds()) {
5334                final int packageCount = mPackages.size();
5335                for (int i = 0; i < packageCount; i++) {
5336                    PackageParser.Package pkg = mPackages.valueAt(i);
5337                    if (!(pkg.mExtras instanceof PackageSetting)) {
5338                        continue;
5339                    }
5340                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5341                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5342                }
5343            }
5344        }
5345    }
5346
5347    @Override
5348    public int getPermissionFlags(String permName, String packageName, int userId) {
5349        return mPermissionManager.getPermissionFlags(
5350                permName, packageName, getCallingUid(), userId);
5351    }
5352
5353    @Override
5354    public void updatePermissionFlags(String permName, String packageName, int flagMask,
5355            int flagValues, int userId) {
5356        mPermissionManager.updatePermissionFlags(
5357                permName, packageName, flagMask, flagValues, getCallingUid(), userId,
5358                mPermissionCallback);
5359    }
5360
5361    /**
5362     * Update the permission flags for all packages and runtime permissions of a user in order
5363     * to allow device or profile owner to remove POLICY_FIXED.
5364     */
5365    @Override
5366    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5367        synchronized (mPackages) {
5368            final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5369                    flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5370                    mPermissionCallback);
5371            if (changed) {
5372                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5373            }
5374        }
5375    }
5376
5377    @Override
5378    public boolean shouldShowRequestPermissionRationale(String permissionName,
5379            String packageName, int userId) {
5380        if (UserHandle.getCallingUserId() != userId) {
5381            mContext.enforceCallingPermission(
5382                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5383                    "canShowRequestPermissionRationale for user " + userId);
5384        }
5385
5386        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5387        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5388            return false;
5389        }
5390
5391        if (checkPermission(permissionName, packageName, userId)
5392                == PackageManager.PERMISSION_GRANTED) {
5393            return false;
5394        }
5395
5396        final int flags;
5397
5398        final long identity = Binder.clearCallingIdentity();
5399        try {
5400            flags = getPermissionFlags(permissionName,
5401                    packageName, userId);
5402        } finally {
5403            Binder.restoreCallingIdentity(identity);
5404        }
5405
5406        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5407                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5408                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5409
5410        if ((flags & fixedFlags) != 0) {
5411            return false;
5412        }
5413
5414        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5415    }
5416
5417    @Override
5418    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5419        mContext.enforceCallingOrSelfPermission(
5420                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5421                "addOnPermissionsChangeListener");
5422
5423        synchronized (mPackages) {
5424            mOnPermissionChangeListeners.addListenerLocked(listener);
5425        }
5426    }
5427
5428    @Override
5429    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5430        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5431            throw new SecurityException("Instant applications don't have access to this method");
5432        }
5433        synchronized (mPackages) {
5434            mOnPermissionChangeListeners.removeListenerLocked(listener);
5435        }
5436    }
5437
5438    @Override
5439    public boolean isProtectedBroadcast(String actionName) {
5440        // allow instant applications
5441        synchronized (mProtectedBroadcasts) {
5442            if (mProtectedBroadcasts.contains(actionName)) {
5443                return true;
5444            } else if (actionName != null) {
5445                // TODO: remove these terrible hacks
5446                if (actionName.startsWith("android.net.netmon.lingerExpired")
5447                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5448                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5449                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5450                    return true;
5451                }
5452            }
5453        }
5454        return false;
5455    }
5456
5457    @Override
5458    public int checkSignatures(String pkg1, String pkg2) {
5459        synchronized (mPackages) {
5460            final PackageParser.Package p1 = mPackages.get(pkg1);
5461            final PackageParser.Package p2 = mPackages.get(pkg2);
5462            if (p1 == null || p1.mExtras == null
5463                    || p2 == null || p2.mExtras == null) {
5464                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5465            }
5466            final int callingUid = Binder.getCallingUid();
5467            final int callingUserId = UserHandle.getUserId(callingUid);
5468            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5469            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5470            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5471                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5472                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5473            }
5474            return compareSignatures(p1.mSigningDetails.signatures, p2.mSigningDetails.signatures);
5475        }
5476    }
5477
5478    @Override
5479    public int checkUidSignatures(int uid1, int uid2) {
5480        final int callingUid = Binder.getCallingUid();
5481        final int callingUserId = UserHandle.getUserId(callingUid);
5482        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5483        // Map to base uids.
5484        uid1 = UserHandle.getAppId(uid1);
5485        uid2 = UserHandle.getAppId(uid2);
5486        // reader
5487        synchronized (mPackages) {
5488            Signature[] s1;
5489            Signature[] s2;
5490            Object obj = mSettings.getUserIdLPr(uid1);
5491            if (obj != null) {
5492                if (obj instanceof SharedUserSetting) {
5493                    if (isCallerInstantApp) {
5494                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5495                    }
5496                    s1 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5497                } else if (obj instanceof PackageSetting) {
5498                    final PackageSetting ps = (PackageSetting) obj;
5499                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5500                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5501                    }
5502                    s1 = ps.signatures.mSigningDetails.signatures;
5503                } else {
5504                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5505                }
5506            } else {
5507                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5508            }
5509            obj = mSettings.getUserIdLPr(uid2);
5510            if (obj != null) {
5511                if (obj instanceof SharedUserSetting) {
5512                    if (isCallerInstantApp) {
5513                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5514                    }
5515                    s2 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5516                } else if (obj instanceof PackageSetting) {
5517                    final PackageSetting ps = (PackageSetting) obj;
5518                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5519                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5520                    }
5521                    s2 = ps.signatures.mSigningDetails.signatures;
5522                } else {
5523                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5524                }
5525            } else {
5526                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5527            }
5528            return compareSignatures(s1, s2);
5529        }
5530    }
5531
5532    @Override
5533    public boolean hasSigningCertificate(
5534            String packageName, byte[] certificate, @PackageManager.CertificateInputType int type) {
5535
5536        synchronized (mPackages) {
5537            final PackageParser.Package p = mPackages.get(packageName);
5538            if (p == null || p.mExtras == null) {
5539                return false;
5540            }
5541            final int callingUid = Binder.getCallingUid();
5542            final int callingUserId = UserHandle.getUserId(callingUid);
5543            final PackageSetting ps = (PackageSetting) p.mExtras;
5544            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5545                return false;
5546            }
5547            switch (type) {
5548                case CERT_INPUT_RAW_X509:
5549                    return signingDetailsHasCertificate(certificate, p.mSigningDetails);
5550                case CERT_INPUT_SHA256:
5551                    return signingDetailsHasSha256Certificate(certificate, p.mSigningDetails);
5552                default:
5553                    return false;
5554            }
5555        }
5556    }
5557
5558    @Override
5559    public boolean hasUidSigningCertificate(
5560            int uid, byte[] certificate, @PackageManager.CertificateInputType int type) {
5561        final int callingUid = Binder.getCallingUid();
5562        final int callingUserId = UserHandle.getUserId(callingUid);
5563        // Map to base uids.
5564        uid = UserHandle.getAppId(uid);
5565        // reader
5566        synchronized (mPackages) {
5567            final PackageParser.SigningDetails signingDetails;
5568            final Object obj = mSettings.getUserIdLPr(uid);
5569            if (obj != null) {
5570                if (obj instanceof SharedUserSetting) {
5571                    final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5572                    if (isCallerInstantApp) {
5573                        return false;
5574                    }
5575                    signingDetails = ((SharedUserSetting)obj).signatures.mSigningDetails;
5576                } else if (obj instanceof PackageSetting) {
5577                    final PackageSetting ps = (PackageSetting) obj;
5578                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5579                        return false;
5580                    }
5581                    signingDetails = ps.signatures.mSigningDetails;
5582                } else {
5583                    return false;
5584                }
5585            } else {
5586                return false;
5587            }
5588            switch (type) {
5589                case CERT_INPUT_RAW_X509:
5590                    return signingDetailsHasCertificate(certificate, signingDetails);
5591                case CERT_INPUT_SHA256:
5592                    return signingDetailsHasSha256Certificate(certificate, signingDetails);
5593                default:
5594                    return false;
5595            }
5596        }
5597    }
5598
5599    /**
5600     * This method should typically only be used when granting or revoking
5601     * permissions, since the app may immediately restart after this call.
5602     * <p>
5603     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5604     * guard your work against the app being relaunched.
5605     */
5606    private void killUid(int appId, int userId, String reason) {
5607        final long identity = Binder.clearCallingIdentity();
5608        try {
5609            IActivityManager am = ActivityManager.getService();
5610            if (am != null) {
5611                try {
5612                    am.killUid(appId, userId, reason);
5613                } catch (RemoteException e) {
5614                    /* ignore - same process */
5615                }
5616            }
5617        } finally {
5618            Binder.restoreCallingIdentity(identity);
5619        }
5620    }
5621
5622    /**
5623     * If the database version for this type of package (internal storage or
5624     * external storage) is less than the version where package signatures
5625     * were updated, return true.
5626     */
5627    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5628        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5629        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5630    }
5631
5632    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5633        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5634        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5635    }
5636
5637    @Override
5638    public List<String> getAllPackages() {
5639        final int callingUid = Binder.getCallingUid();
5640        final int callingUserId = UserHandle.getUserId(callingUid);
5641        synchronized (mPackages) {
5642            if (canViewInstantApps(callingUid, callingUserId)) {
5643                return new ArrayList<String>(mPackages.keySet());
5644            }
5645            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5646            final List<String> result = new ArrayList<>();
5647            if (instantAppPkgName != null) {
5648                // caller is an instant application; filter unexposed applications
5649                for (PackageParser.Package pkg : mPackages.values()) {
5650                    if (!pkg.visibleToInstantApps) {
5651                        continue;
5652                    }
5653                    result.add(pkg.packageName);
5654                }
5655            } else {
5656                // caller is a normal application; filter instant applications
5657                for (PackageParser.Package pkg : mPackages.values()) {
5658                    final PackageSetting ps =
5659                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5660                    if (ps != null
5661                            && ps.getInstantApp(callingUserId)
5662                            && !mInstantAppRegistry.isInstantAccessGranted(
5663                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5664                        continue;
5665                    }
5666                    result.add(pkg.packageName);
5667                }
5668            }
5669            return result;
5670        }
5671    }
5672
5673    @Override
5674    public String[] getPackagesForUid(int uid) {
5675        final int callingUid = Binder.getCallingUid();
5676        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5677        final int userId = UserHandle.getUserId(uid);
5678        uid = UserHandle.getAppId(uid);
5679        // reader
5680        synchronized (mPackages) {
5681            Object obj = mSettings.getUserIdLPr(uid);
5682            if (obj instanceof SharedUserSetting) {
5683                if (isCallerInstantApp) {
5684                    return null;
5685                }
5686                final SharedUserSetting sus = (SharedUserSetting) obj;
5687                final int N = sus.packages.size();
5688                String[] res = new String[N];
5689                final Iterator<PackageSetting> it = sus.packages.iterator();
5690                int i = 0;
5691                while (it.hasNext()) {
5692                    PackageSetting ps = it.next();
5693                    if (ps.getInstalled(userId)) {
5694                        res[i++] = ps.name;
5695                    } else {
5696                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5697                    }
5698                }
5699                return res;
5700            } else if (obj instanceof PackageSetting) {
5701                final PackageSetting ps = (PackageSetting) obj;
5702                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5703                    return new String[]{ps.name};
5704                }
5705            }
5706        }
5707        return null;
5708    }
5709
5710    @Override
5711    public String getNameForUid(int uid) {
5712        final int callingUid = Binder.getCallingUid();
5713        if (getInstantAppPackageName(callingUid) != null) {
5714            return null;
5715        }
5716        synchronized (mPackages) {
5717            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5718            if (obj instanceof SharedUserSetting) {
5719                final SharedUserSetting sus = (SharedUserSetting) obj;
5720                return sus.name + ":" + sus.userId;
5721            } else if (obj instanceof PackageSetting) {
5722                final PackageSetting ps = (PackageSetting) obj;
5723                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5724                    return null;
5725                }
5726                return ps.name;
5727            }
5728            return null;
5729        }
5730    }
5731
5732    @Override
5733    public String[] getNamesForUids(int[] uids) {
5734        if (uids == null || uids.length == 0) {
5735            return null;
5736        }
5737        final int callingUid = Binder.getCallingUid();
5738        if (getInstantAppPackageName(callingUid) != null) {
5739            return null;
5740        }
5741        final String[] names = new String[uids.length];
5742        synchronized (mPackages) {
5743            for (int i = uids.length - 1; i >= 0; i--) {
5744                final int uid = uids[i];
5745                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5746                if (obj instanceof SharedUserSetting) {
5747                    final SharedUserSetting sus = (SharedUserSetting) obj;
5748                    names[i] = "shared:" + sus.name;
5749                } else if (obj instanceof PackageSetting) {
5750                    final PackageSetting ps = (PackageSetting) obj;
5751                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5752                        names[i] = null;
5753                    } else {
5754                        names[i] = ps.name;
5755                    }
5756                } else {
5757                    names[i] = null;
5758                }
5759            }
5760        }
5761        return names;
5762    }
5763
5764    @Override
5765    public int getUidForSharedUser(String sharedUserName) {
5766        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5767            return -1;
5768        }
5769        if (sharedUserName == null) {
5770            return -1;
5771        }
5772        // reader
5773        synchronized (mPackages) {
5774            SharedUserSetting suid;
5775            try {
5776                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5777                if (suid != null) {
5778                    return suid.userId;
5779                }
5780            } catch (PackageManagerException ignore) {
5781                // can't happen, but, still need to catch it
5782            }
5783            return -1;
5784        }
5785    }
5786
5787    @Override
5788    public int getFlagsForUid(int uid) {
5789        final int callingUid = Binder.getCallingUid();
5790        if (getInstantAppPackageName(callingUid) != null) {
5791            return 0;
5792        }
5793        synchronized (mPackages) {
5794            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5795            if (obj instanceof SharedUserSetting) {
5796                final SharedUserSetting sus = (SharedUserSetting) obj;
5797                return sus.pkgFlags;
5798            } else if (obj instanceof PackageSetting) {
5799                final PackageSetting ps = (PackageSetting) obj;
5800                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5801                    return 0;
5802                }
5803                return ps.pkgFlags;
5804            }
5805        }
5806        return 0;
5807    }
5808
5809    @Override
5810    public int getPrivateFlagsForUid(int uid) {
5811        final int callingUid = Binder.getCallingUid();
5812        if (getInstantAppPackageName(callingUid) != null) {
5813            return 0;
5814        }
5815        synchronized (mPackages) {
5816            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5817            if (obj instanceof SharedUserSetting) {
5818                final SharedUserSetting sus = (SharedUserSetting) obj;
5819                return sus.pkgPrivateFlags;
5820            } else if (obj instanceof PackageSetting) {
5821                final PackageSetting ps = (PackageSetting) obj;
5822                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5823                    return 0;
5824                }
5825                return ps.pkgPrivateFlags;
5826            }
5827        }
5828        return 0;
5829    }
5830
5831    @Override
5832    public boolean isUidPrivileged(int uid) {
5833        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5834            return false;
5835        }
5836        uid = UserHandle.getAppId(uid);
5837        // reader
5838        synchronized (mPackages) {
5839            Object obj = mSettings.getUserIdLPr(uid);
5840            if (obj instanceof SharedUserSetting) {
5841                final SharedUserSetting sus = (SharedUserSetting) obj;
5842                final Iterator<PackageSetting> it = sus.packages.iterator();
5843                while (it.hasNext()) {
5844                    if (it.next().isPrivileged()) {
5845                        return true;
5846                    }
5847                }
5848            } else if (obj instanceof PackageSetting) {
5849                final PackageSetting ps = (PackageSetting) obj;
5850                return ps.isPrivileged();
5851            }
5852        }
5853        return false;
5854    }
5855
5856    @Override
5857    public String[] getAppOpPermissionPackages(String permName) {
5858        return mPermissionManager.getAppOpPermissionPackages(permName);
5859    }
5860
5861    @Override
5862    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5863            int flags, int userId) {
5864        return resolveIntentInternal(
5865                intent, resolvedType, flags, userId, false /*resolveForStart*/);
5866    }
5867
5868    /**
5869     * Normally instant apps can only be resolved when they're visible to the caller.
5870     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
5871     * since we need to allow the system to start any installed application.
5872     */
5873    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5874            int flags, int userId, boolean resolveForStart) {
5875        try {
5876            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5877
5878            if (!sUserManager.exists(userId)) return null;
5879            final int callingUid = Binder.getCallingUid();
5880            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
5881            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5882                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5883
5884            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5885            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5886                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
5887            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5888
5889            final ResolveInfo bestChoice =
5890                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5891            return bestChoice;
5892        } finally {
5893            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5894        }
5895    }
5896
5897    @Override
5898    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5899        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5900            throw new SecurityException(
5901                    "findPersistentPreferredActivity can only be run by the system");
5902        }
5903        if (!sUserManager.exists(userId)) {
5904            return null;
5905        }
5906        final int callingUid = Binder.getCallingUid();
5907        intent = updateIntentForResolve(intent);
5908        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5909        final int flags = updateFlagsForResolve(
5910                0, userId, intent, callingUid, false /*includeInstantApps*/);
5911        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5912                userId);
5913        synchronized (mPackages) {
5914            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5915                    userId);
5916        }
5917    }
5918
5919    @Override
5920    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5921            IntentFilter filter, int match, ComponentName activity) {
5922        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5923            return;
5924        }
5925        final int userId = UserHandle.getCallingUserId();
5926        if (DEBUG_PREFERRED) {
5927            Log.v(TAG, "setLastChosenActivity intent=" + intent
5928                + " resolvedType=" + resolvedType
5929                + " flags=" + flags
5930                + " filter=" + filter
5931                + " match=" + match
5932                + " activity=" + activity);
5933            filter.dump(new PrintStreamPrinter(System.out), "    ");
5934        }
5935        intent.setComponent(null);
5936        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5937                userId);
5938        // Find any earlier preferred or last chosen entries and nuke them
5939        findPreferredActivity(intent, resolvedType,
5940                flags, query, 0, false, true, false, userId);
5941        // Add the new activity as the last chosen for this filter
5942        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5943                "Setting last chosen");
5944    }
5945
5946    @Override
5947    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5948        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5949            return null;
5950        }
5951        final int userId = UserHandle.getCallingUserId();
5952        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5953        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5954                userId);
5955        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5956                false, false, false, userId);
5957    }
5958
5959    /**
5960     * Returns whether or not instant apps have been disabled remotely.
5961     */
5962    private boolean isEphemeralDisabled() {
5963        return mEphemeralAppsDisabled;
5964    }
5965
5966    private boolean isInstantAppAllowed(
5967            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5968            boolean skipPackageCheck) {
5969        if (mInstantAppResolverConnection == null) {
5970            return false;
5971        }
5972        if (mInstantAppInstallerActivity == null) {
5973            return false;
5974        }
5975        if (intent.getComponent() != null) {
5976            return false;
5977        }
5978        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5979            return false;
5980        }
5981        if (!skipPackageCheck && intent.getPackage() != null) {
5982            return false;
5983        }
5984        if (!intent.isBrowsableWebIntent()) {
5985            // for non web intents, we should not resolve externally if an app already exists to
5986            // handle it or if the caller didn't explicitly request it.
5987            if ((resolvedActivities != null && resolvedActivities.size() != 0)
5988                    || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) == 0) {
5989                return false;
5990            }
5991        } else if (intent.getData() == null) {
5992            return false;
5993        }
5994        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5995        // Or if there's already an ephemeral app installed that handles the action
5996        synchronized (mPackages) {
5997            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5998            for (int n = 0; n < count; n++) {
5999                final ResolveInfo info = resolvedActivities.get(n);
6000                final String packageName = info.activityInfo.packageName;
6001                final PackageSetting ps = mSettings.mPackages.get(packageName);
6002                if (ps != null) {
6003                    // only check domain verification status if the app is not a browser
6004                    if (!info.handleAllWebDataURI) {
6005                        // Try to get the status from User settings first
6006                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6007                        final int status = (int) (packedStatus >> 32);
6008                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6009                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6010                            if (DEBUG_EPHEMERAL) {
6011                                Slog.v(TAG, "DENY instant app;"
6012                                    + " pkg: " + packageName + ", status: " + status);
6013                            }
6014                            return false;
6015                        }
6016                    }
6017                    if (ps.getInstantApp(userId)) {
6018                        if (DEBUG_EPHEMERAL) {
6019                            Slog.v(TAG, "DENY instant app installed;"
6020                                    + " pkg: " + packageName);
6021                        }
6022                        return false;
6023                    }
6024                }
6025            }
6026        }
6027        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6028        return true;
6029    }
6030
6031    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6032            Intent origIntent, String resolvedType, String callingPackage,
6033            Bundle verificationBundle, int userId) {
6034        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6035                new InstantAppRequest(responseObj, origIntent, resolvedType,
6036                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6037        mHandler.sendMessage(msg);
6038    }
6039
6040    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6041            int flags, List<ResolveInfo> query, int userId) {
6042        if (query != null) {
6043            final int N = query.size();
6044            if (N == 1) {
6045                return query.get(0);
6046            } else if (N > 1) {
6047                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6048                // If there is more than one activity with the same priority,
6049                // then let the user decide between them.
6050                ResolveInfo r0 = query.get(0);
6051                ResolveInfo r1 = query.get(1);
6052                if (DEBUG_INTENT_MATCHING || debug) {
6053                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6054                            + r1.activityInfo.name + "=" + r1.priority);
6055                }
6056                // If the first activity has a higher priority, or a different
6057                // default, then it is always desirable to pick it.
6058                if (r0.priority != r1.priority
6059                        || r0.preferredOrder != r1.preferredOrder
6060                        || r0.isDefault != r1.isDefault) {
6061                    return query.get(0);
6062                }
6063                // If we have saved a preference for a preferred activity for
6064                // this Intent, use that.
6065                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6066                        flags, query, r0.priority, true, false, debug, userId);
6067                if (ri != null) {
6068                    return ri;
6069                }
6070                // If we have an ephemeral app, use it
6071                for (int i = 0; i < N; i++) {
6072                    ri = query.get(i);
6073                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6074                        final String packageName = ri.activityInfo.packageName;
6075                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6076                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6077                        final int status = (int)(packedStatus >> 32);
6078                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6079                            return ri;
6080                        }
6081                    }
6082                }
6083                ri = new ResolveInfo(mResolveInfo);
6084                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6085                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6086                // If all of the options come from the same package, show the application's
6087                // label and icon instead of the generic resolver's.
6088                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6089                // and then throw away the ResolveInfo itself, meaning that the caller loses
6090                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6091                // a fallback for this case; we only set the target package's resources on
6092                // the ResolveInfo, not the ActivityInfo.
6093                final String intentPackage = intent.getPackage();
6094                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6095                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6096                    ri.resolvePackageName = intentPackage;
6097                    if (userNeedsBadging(userId)) {
6098                        ri.noResourceId = true;
6099                    } else {
6100                        ri.icon = appi.icon;
6101                    }
6102                    ri.iconResourceId = appi.icon;
6103                    ri.labelRes = appi.labelRes;
6104                }
6105                ri.activityInfo.applicationInfo = new ApplicationInfo(
6106                        ri.activityInfo.applicationInfo);
6107                if (userId != 0) {
6108                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6109                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6110                }
6111                // Make sure that the resolver is displayable in car mode
6112                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6113                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6114                return ri;
6115            }
6116        }
6117        return null;
6118    }
6119
6120    /**
6121     * Return true if the given list is not empty and all of its contents have
6122     * an activityInfo with the given package name.
6123     */
6124    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6125        if (ArrayUtils.isEmpty(list)) {
6126            return false;
6127        }
6128        for (int i = 0, N = list.size(); i < N; i++) {
6129            final ResolveInfo ri = list.get(i);
6130            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6131            if (ai == null || !packageName.equals(ai.packageName)) {
6132                return false;
6133            }
6134        }
6135        return true;
6136    }
6137
6138    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6139            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6140        final int N = query.size();
6141        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6142                .get(userId);
6143        // Get the list of persistent preferred activities that handle the intent
6144        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6145        List<PersistentPreferredActivity> pprefs = ppir != null
6146                ? ppir.queryIntent(intent, resolvedType,
6147                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6148                        userId)
6149                : null;
6150        if (pprefs != null && pprefs.size() > 0) {
6151            final int M = pprefs.size();
6152            for (int i=0; i<M; i++) {
6153                final PersistentPreferredActivity ppa = pprefs.get(i);
6154                if (DEBUG_PREFERRED || debug) {
6155                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6156                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6157                            + "\n  component=" + ppa.mComponent);
6158                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6159                }
6160                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6161                        flags | MATCH_DISABLED_COMPONENTS, userId);
6162                if (DEBUG_PREFERRED || debug) {
6163                    Slog.v(TAG, "Found persistent preferred activity:");
6164                    if (ai != null) {
6165                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6166                    } else {
6167                        Slog.v(TAG, "  null");
6168                    }
6169                }
6170                if (ai == null) {
6171                    // This previously registered persistent preferred activity
6172                    // component is no longer known. Ignore it and do NOT remove it.
6173                    continue;
6174                }
6175                for (int j=0; j<N; j++) {
6176                    final ResolveInfo ri = query.get(j);
6177                    if (!ri.activityInfo.applicationInfo.packageName
6178                            .equals(ai.applicationInfo.packageName)) {
6179                        continue;
6180                    }
6181                    if (!ri.activityInfo.name.equals(ai.name)) {
6182                        continue;
6183                    }
6184                    //  Found a persistent preference that can handle the intent.
6185                    if (DEBUG_PREFERRED || debug) {
6186                        Slog.v(TAG, "Returning persistent preferred activity: " +
6187                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6188                    }
6189                    return ri;
6190                }
6191            }
6192        }
6193        return null;
6194    }
6195
6196    // TODO: handle preferred activities missing while user has amnesia
6197    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6198            List<ResolveInfo> query, int priority, boolean always,
6199            boolean removeMatches, boolean debug, int userId) {
6200        if (!sUserManager.exists(userId)) return null;
6201        final int callingUid = Binder.getCallingUid();
6202        flags = updateFlagsForResolve(
6203                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6204        intent = updateIntentForResolve(intent);
6205        // writer
6206        synchronized (mPackages) {
6207            // Try to find a matching persistent preferred activity.
6208            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6209                    debug, userId);
6210
6211            // If a persistent preferred activity matched, use it.
6212            if (pri != null) {
6213                return pri;
6214            }
6215
6216            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6217            // Get the list of preferred activities that handle the intent
6218            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6219            List<PreferredActivity> prefs = pir != null
6220                    ? pir.queryIntent(intent, resolvedType,
6221                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6222                            userId)
6223                    : null;
6224            if (prefs != null && prefs.size() > 0) {
6225                boolean changed = false;
6226                try {
6227                    // First figure out how good the original match set is.
6228                    // We will only allow preferred activities that came
6229                    // from the same match quality.
6230                    int match = 0;
6231
6232                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6233
6234                    final int N = query.size();
6235                    for (int j=0; j<N; j++) {
6236                        final ResolveInfo ri = query.get(j);
6237                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6238                                + ": 0x" + Integer.toHexString(match));
6239                        if (ri.match > match) {
6240                            match = ri.match;
6241                        }
6242                    }
6243
6244                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6245                            + Integer.toHexString(match));
6246
6247                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6248                    final int M = prefs.size();
6249                    for (int i=0; i<M; i++) {
6250                        final PreferredActivity pa = prefs.get(i);
6251                        if (DEBUG_PREFERRED || debug) {
6252                            Slog.v(TAG, "Checking PreferredActivity ds="
6253                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6254                                    + "\n  component=" + pa.mPref.mComponent);
6255                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6256                        }
6257                        if (pa.mPref.mMatch != match) {
6258                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6259                                    + Integer.toHexString(pa.mPref.mMatch));
6260                            continue;
6261                        }
6262                        // If it's not an "always" type preferred activity and that's what we're
6263                        // looking for, skip it.
6264                        if (always && !pa.mPref.mAlways) {
6265                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6266                            continue;
6267                        }
6268                        final ActivityInfo ai = getActivityInfo(
6269                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6270                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6271                                userId);
6272                        if (DEBUG_PREFERRED || debug) {
6273                            Slog.v(TAG, "Found preferred activity:");
6274                            if (ai != null) {
6275                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6276                            } else {
6277                                Slog.v(TAG, "  null");
6278                            }
6279                        }
6280                        if (ai == null) {
6281                            // This previously registered preferred activity
6282                            // component is no longer known.  Most likely an update
6283                            // to the app was installed and in the new version this
6284                            // component no longer exists.  Clean it up by removing
6285                            // it from the preferred activities list, and skip it.
6286                            Slog.w(TAG, "Removing dangling preferred activity: "
6287                                    + pa.mPref.mComponent);
6288                            pir.removeFilter(pa);
6289                            changed = true;
6290                            continue;
6291                        }
6292                        for (int j=0; j<N; j++) {
6293                            final ResolveInfo ri = query.get(j);
6294                            if (!ri.activityInfo.applicationInfo.packageName
6295                                    .equals(ai.applicationInfo.packageName)) {
6296                                continue;
6297                            }
6298                            if (!ri.activityInfo.name.equals(ai.name)) {
6299                                continue;
6300                            }
6301
6302                            if (removeMatches) {
6303                                pir.removeFilter(pa);
6304                                changed = true;
6305                                if (DEBUG_PREFERRED) {
6306                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6307                                }
6308                                break;
6309                            }
6310
6311                            // Okay we found a previously set preferred or last chosen app.
6312                            // If the result set is different from when this
6313                            // was created, and is not a subset of the preferred set, we need to
6314                            // clear it and re-ask the user their preference, if we're looking for
6315                            // an "always" type entry.
6316                            if (always && !pa.mPref.sameSet(query)) {
6317                                if (pa.mPref.isSuperset(query)) {
6318                                    // some components of the set are no longer present in
6319                                    // the query, but the preferred activity can still be reused
6320                                    if (DEBUG_PREFERRED) {
6321                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6322                                                + " still valid as only non-preferred components"
6323                                                + " were removed for " + intent + " type "
6324                                                + resolvedType);
6325                                    }
6326                                    // remove obsolete components and re-add the up-to-date filter
6327                                    PreferredActivity freshPa = new PreferredActivity(pa,
6328                                            pa.mPref.mMatch,
6329                                            pa.mPref.discardObsoleteComponents(query),
6330                                            pa.mPref.mComponent,
6331                                            pa.mPref.mAlways);
6332                                    pir.removeFilter(pa);
6333                                    pir.addFilter(freshPa);
6334                                    changed = true;
6335                                } else {
6336                                    Slog.i(TAG,
6337                                            "Result set changed, dropping preferred activity for "
6338                                                    + intent + " type " + resolvedType);
6339                                    if (DEBUG_PREFERRED) {
6340                                        Slog.v(TAG, "Removing preferred activity since set changed "
6341                                                + pa.mPref.mComponent);
6342                                    }
6343                                    pir.removeFilter(pa);
6344                                    // Re-add the filter as a "last chosen" entry (!always)
6345                                    PreferredActivity lastChosen = new PreferredActivity(
6346                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6347                                    pir.addFilter(lastChosen);
6348                                    changed = true;
6349                                    return null;
6350                                }
6351                            }
6352
6353                            // Yay! Either the set matched or we're looking for the last chosen
6354                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6355                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6356                            return ri;
6357                        }
6358                    }
6359                } finally {
6360                    if (changed) {
6361                        if (DEBUG_PREFERRED) {
6362                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6363                        }
6364                        scheduleWritePackageRestrictionsLocked(userId);
6365                    }
6366                }
6367            }
6368        }
6369        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6370        return null;
6371    }
6372
6373    /*
6374     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6375     */
6376    @Override
6377    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6378            int targetUserId) {
6379        mContext.enforceCallingOrSelfPermission(
6380                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6381        List<CrossProfileIntentFilter> matches =
6382                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6383        if (matches != null) {
6384            int size = matches.size();
6385            for (int i = 0; i < size; i++) {
6386                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6387            }
6388        }
6389        if (intent.hasWebURI()) {
6390            // cross-profile app linking works only towards the parent.
6391            final int callingUid = Binder.getCallingUid();
6392            final UserInfo parent = getProfileParent(sourceUserId);
6393            synchronized(mPackages) {
6394                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6395                        false /*includeInstantApps*/);
6396                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6397                        intent, resolvedType, flags, sourceUserId, parent.id);
6398                return xpDomainInfo != null;
6399            }
6400        }
6401        return false;
6402    }
6403
6404    private UserInfo getProfileParent(int userId) {
6405        final long identity = Binder.clearCallingIdentity();
6406        try {
6407            return sUserManager.getProfileParent(userId);
6408        } finally {
6409            Binder.restoreCallingIdentity(identity);
6410        }
6411    }
6412
6413    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6414            String resolvedType, int userId) {
6415        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6416        if (resolver != null) {
6417            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6418        }
6419        return null;
6420    }
6421
6422    @Override
6423    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6424            String resolvedType, int flags, int userId) {
6425        try {
6426            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6427
6428            return new ParceledListSlice<>(
6429                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6430        } finally {
6431            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6432        }
6433    }
6434
6435    /**
6436     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6437     * instant, returns {@code null}.
6438     */
6439    private String getInstantAppPackageName(int callingUid) {
6440        synchronized (mPackages) {
6441            // If the caller is an isolated app use the owner's uid for the lookup.
6442            if (Process.isIsolated(callingUid)) {
6443                callingUid = mIsolatedOwners.get(callingUid);
6444            }
6445            final int appId = UserHandle.getAppId(callingUid);
6446            final Object obj = mSettings.getUserIdLPr(appId);
6447            if (obj instanceof PackageSetting) {
6448                final PackageSetting ps = (PackageSetting) obj;
6449                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6450                return isInstantApp ? ps.pkg.packageName : null;
6451            }
6452        }
6453        return null;
6454    }
6455
6456    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6457            String resolvedType, int flags, int userId) {
6458        return queryIntentActivitiesInternal(
6459                intent, resolvedType, flags, Binder.getCallingUid(), userId,
6460                false /*resolveForStart*/, true /*allowDynamicSplits*/);
6461    }
6462
6463    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6464            String resolvedType, int flags, int filterCallingUid, int userId,
6465            boolean resolveForStart, boolean allowDynamicSplits) {
6466        if (!sUserManager.exists(userId)) return Collections.emptyList();
6467        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6468        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6469                false /* requireFullPermission */, false /* checkShell */,
6470                "query intent activities");
6471        final String pkgName = intent.getPackage();
6472        ComponentName comp = intent.getComponent();
6473        if (comp == null) {
6474            if (intent.getSelector() != null) {
6475                intent = intent.getSelector();
6476                comp = intent.getComponent();
6477            }
6478        }
6479
6480        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6481                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6482        if (comp != null) {
6483            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6484            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6485            if (ai != null) {
6486                // When specifying an explicit component, we prevent the activity from being
6487                // used when either 1) the calling package is normal and the activity is within
6488                // an ephemeral application or 2) the calling package is ephemeral and the
6489                // activity is not visible to ephemeral applications.
6490                final boolean matchInstantApp =
6491                        (flags & PackageManager.MATCH_INSTANT) != 0;
6492                final boolean matchVisibleToInstantAppOnly =
6493                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6494                final boolean matchExplicitlyVisibleOnly =
6495                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6496                final boolean isCallerInstantApp =
6497                        instantAppPkgName != null;
6498                final boolean isTargetSameInstantApp =
6499                        comp.getPackageName().equals(instantAppPkgName);
6500                final boolean isTargetInstantApp =
6501                        (ai.applicationInfo.privateFlags
6502                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6503                final boolean isTargetVisibleToInstantApp =
6504                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6505                final boolean isTargetExplicitlyVisibleToInstantApp =
6506                        isTargetVisibleToInstantApp
6507                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6508                final boolean isTargetHiddenFromInstantApp =
6509                        !isTargetVisibleToInstantApp
6510                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6511                final boolean blockResolution =
6512                        !isTargetSameInstantApp
6513                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6514                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6515                                        && isTargetHiddenFromInstantApp));
6516                if (!blockResolution) {
6517                    final ResolveInfo ri = new ResolveInfo();
6518                    ri.activityInfo = ai;
6519                    list.add(ri);
6520                }
6521            }
6522            return applyPostResolutionFilter(
6523                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6524        }
6525
6526        // reader
6527        boolean sortResult = false;
6528        boolean addEphemeral = false;
6529        List<ResolveInfo> result;
6530        final boolean ephemeralDisabled = isEphemeralDisabled();
6531        synchronized (mPackages) {
6532            if (pkgName == null) {
6533                List<CrossProfileIntentFilter> matchingFilters =
6534                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6535                // Check for results that need to skip the current profile.
6536                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6537                        resolvedType, flags, userId);
6538                if (xpResolveInfo != null) {
6539                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6540                    xpResult.add(xpResolveInfo);
6541                    return applyPostResolutionFilter(
6542                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6543                            allowDynamicSplits, filterCallingUid, userId);
6544                }
6545
6546                // Check for results in the current profile.
6547                result = filterIfNotSystemUser(mActivities.queryIntent(
6548                        intent, resolvedType, flags, userId), userId);
6549                addEphemeral = !ephemeralDisabled
6550                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6551                // Check for cross profile results.
6552                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6553                xpResolveInfo = queryCrossProfileIntents(
6554                        matchingFilters, intent, resolvedType, flags, userId,
6555                        hasNonNegativePriorityResult);
6556                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6557                    boolean isVisibleToUser = filterIfNotSystemUser(
6558                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6559                    if (isVisibleToUser) {
6560                        result.add(xpResolveInfo);
6561                        sortResult = true;
6562                    }
6563                }
6564                if (intent.hasWebURI()) {
6565                    CrossProfileDomainInfo xpDomainInfo = null;
6566                    final UserInfo parent = getProfileParent(userId);
6567                    if (parent != null) {
6568                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6569                                flags, userId, parent.id);
6570                    }
6571                    if (xpDomainInfo != null) {
6572                        if (xpResolveInfo != null) {
6573                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6574                            // in the result.
6575                            result.remove(xpResolveInfo);
6576                        }
6577                        if (result.size() == 0 && !addEphemeral) {
6578                            // No result in current profile, but found candidate in parent user.
6579                            // And we are not going to add emphemeral app, so we can return the
6580                            // result straight away.
6581                            result.add(xpDomainInfo.resolveInfo);
6582                            return applyPostResolutionFilter(result, instantAppPkgName,
6583                                    allowDynamicSplits, filterCallingUid, userId);
6584                        }
6585                    } else if (result.size() <= 1 && !addEphemeral) {
6586                        // No result in parent user and <= 1 result in current profile, and we
6587                        // are not going to add emphemeral app, so we can return the result without
6588                        // further processing.
6589                        return applyPostResolutionFilter(result, instantAppPkgName,
6590                                allowDynamicSplits, filterCallingUid, userId);
6591                    }
6592                    // We have more than one candidate (combining results from current and parent
6593                    // profile), so we need filtering and sorting.
6594                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6595                            intent, flags, result, xpDomainInfo, userId);
6596                    sortResult = true;
6597                }
6598            } else {
6599                final PackageParser.Package pkg = mPackages.get(pkgName);
6600                result = null;
6601                if (pkg != null) {
6602                    result = filterIfNotSystemUser(
6603                            mActivities.queryIntentForPackage(
6604                                    intent, resolvedType, flags, pkg.activities, userId),
6605                            userId);
6606                }
6607                if (result == null || result.size() == 0) {
6608                    // the caller wants to resolve for a particular package; however, there
6609                    // were no installed results, so, try to find an ephemeral result
6610                    addEphemeral = !ephemeralDisabled
6611                            && isInstantAppAllowed(
6612                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6613                    if (result == null) {
6614                        result = new ArrayList<>();
6615                    }
6616                }
6617            }
6618        }
6619        if (addEphemeral) {
6620            result = maybeAddInstantAppInstaller(
6621                    result, intent, resolvedType, flags, userId, resolveForStart);
6622        }
6623        if (sortResult) {
6624            Collections.sort(result, mResolvePrioritySorter);
6625        }
6626        return applyPostResolutionFilter(
6627                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6628    }
6629
6630    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6631            String resolvedType, int flags, int userId, boolean resolveForStart) {
6632        // first, check to see if we've got an instant app already installed
6633        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6634        ResolveInfo localInstantApp = null;
6635        boolean blockResolution = false;
6636        if (!alreadyResolvedLocally) {
6637            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6638                    flags
6639                        | PackageManager.GET_RESOLVED_FILTER
6640                        | PackageManager.MATCH_INSTANT
6641                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6642                    userId);
6643            for (int i = instantApps.size() - 1; i >= 0; --i) {
6644                final ResolveInfo info = instantApps.get(i);
6645                final String packageName = info.activityInfo.packageName;
6646                final PackageSetting ps = mSettings.mPackages.get(packageName);
6647                if (ps.getInstantApp(userId)) {
6648                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6649                    final int status = (int)(packedStatus >> 32);
6650                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6651                        // there's a local instant application installed, but, the user has
6652                        // chosen to never use it; skip resolution and don't acknowledge
6653                        // an instant application is even available
6654                        if (DEBUG_EPHEMERAL) {
6655                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6656                        }
6657                        blockResolution = true;
6658                        break;
6659                    } else {
6660                        // we have a locally installed instant application; skip resolution
6661                        // but acknowledge there's an instant application available
6662                        if (DEBUG_EPHEMERAL) {
6663                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6664                        }
6665                        localInstantApp = info;
6666                        break;
6667                    }
6668                }
6669            }
6670        }
6671        // no app installed, let's see if one's available
6672        AuxiliaryResolveInfo auxiliaryResponse = null;
6673        if (!blockResolution) {
6674            if (localInstantApp == null) {
6675                // we don't have an instant app locally, resolve externally
6676                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6677                final InstantAppRequest requestObject = new InstantAppRequest(
6678                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6679                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6680                        resolveForStart);
6681                auxiliaryResponse = InstantAppResolver.doInstantAppResolutionPhaseOne(
6682                        mInstantAppResolverConnection, requestObject);
6683                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6684            } else {
6685                // we have an instant application locally, but, we can't admit that since
6686                // callers shouldn't be able to determine prior browsing. create a dummy
6687                // auxiliary response so the downstream code behaves as if there's an
6688                // instant application available externally. when it comes time to start
6689                // the instant application, we'll do the right thing.
6690                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6691                auxiliaryResponse = new AuxiliaryResolveInfo(null /* failureActivity */,
6692                                        ai.packageName, ai.versionCode, null /* splitName */);
6693            }
6694        }
6695        if (intent.isBrowsableWebIntent() && auxiliaryResponse == null) {
6696            return result;
6697        }
6698        final PackageSetting ps = mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6699        if (ps == null) {
6700            return result;
6701        }
6702        final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6703        ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6704                mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6705        ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6706                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6707        // add a non-generic filter
6708        ephemeralInstaller.filter = new IntentFilter();
6709        if (intent.getAction() != null) {
6710            ephemeralInstaller.filter.addAction(intent.getAction());
6711        }
6712        if (intent.getData() != null && intent.getData().getPath() != null) {
6713            ephemeralInstaller.filter.addDataPath(
6714                    intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6715        }
6716        ephemeralInstaller.isInstantAppAvailable = true;
6717        // make sure this resolver is the default
6718        ephemeralInstaller.isDefault = true;
6719        ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6720        if (DEBUG_EPHEMERAL) {
6721            Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6722        }
6723
6724        result.add(ephemeralInstaller);
6725        return result;
6726    }
6727
6728    private static class CrossProfileDomainInfo {
6729        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6730        ResolveInfo resolveInfo;
6731        /* Best domain verification status of the activities found in the other profile */
6732        int bestDomainVerificationStatus;
6733    }
6734
6735    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6736            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6737        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6738                sourceUserId)) {
6739            return null;
6740        }
6741        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6742                resolvedType, flags, parentUserId);
6743
6744        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6745            return null;
6746        }
6747        CrossProfileDomainInfo result = null;
6748        int size = resultTargetUser.size();
6749        for (int i = 0; i < size; i++) {
6750            ResolveInfo riTargetUser = resultTargetUser.get(i);
6751            // Intent filter verification is only for filters that specify a host. So don't return
6752            // those that handle all web uris.
6753            if (riTargetUser.handleAllWebDataURI) {
6754                continue;
6755            }
6756            String packageName = riTargetUser.activityInfo.packageName;
6757            PackageSetting ps = mSettings.mPackages.get(packageName);
6758            if (ps == null) {
6759                continue;
6760            }
6761            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6762            int status = (int)(verificationState >> 32);
6763            if (result == null) {
6764                result = new CrossProfileDomainInfo();
6765                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6766                        sourceUserId, parentUserId);
6767                result.bestDomainVerificationStatus = status;
6768            } else {
6769                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6770                        result.bestDomainVerificationStatus);
6771            }
6772        }
6773        // Don't consider matches with status NEVER across profiles.
6774        if (result != null && result.bestDomainVerificationStatus
6775                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6776            return null;
6777        }
6778        return result;
6779    }
6780
6781    /**
6782     * Verification statuses are ordered from the worse to the best, except for
6783     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6784     */
6785    private int bestDomainVerificationStatus(int status1, int status2) {
6786        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6787            return status2;
6788        }
6789        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6790            return status1;
6791        }
6792        return (int) MathUtils.max(status1, status2);
6793    }
6794
6795    private boolean isUserEnabled(int userId) {
6796        long callingId = Binder.clearCallingIdentity();
6797        try {
6798            UserInfo userInfo = sUserManager.getUserInfo(userId);
6799            return userInfo != null && userInfo.isEnabled();
6800        } finally {
6801            Binder.restoreCallingIdentity(callingId);
6802        }
6803    }
6804
6805    /**
6806     * Filter out activities with systemUserOnly flag set, when current user is not System.
6807     *
6808     * @return filtered list
6809     */
6810    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6811        if (userId == UserHandle.USER_SYSTEM) {
6812            return resolveInfos;
6813        }
6814        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6815            ResolveInfo info = resolveInfos.get(i);
6816            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6817                resolveInfos.remove(i);
6818            }
6819        }
6820        return resolveInfos;
6821    }
6822
6823    /**
6824     * Filters out ephemeral activities.
6825     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6826     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6827     *
6828     * @param resolveInfos The pre-filtered list of resolved activities
6829     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6830     *          is performed.
6831     * @return A filtered list of resolved activities.
6832     */
6833    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6834            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) {
6835        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6836            final ResolveInfo info = resolveInfos.get(i);
6837            // allow activities that are defined in the provided package
6838            if (allowDynamicSplits
6839                    && info.activityInfo != null
6840                    && info.activityInfo.splitName != null
6841                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6842                            info.activityInfo.splitName)) {
6843                if (mInstantAppInstallerActivity == null) {
6844                    if (DEBUG_INSTALL) {
6845                        Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
6846                    }
6847                    resolveInfos.remove(i);
6848                    continue;
6849                }
6850                // requested activity is defined in a split that hasn't been installed yet.
6851                // add the installer to the resolve list
6852                if (DEBUG_INSTALL) {
6853                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6854                }
6855                final ResolveInfo installerInfo = new ResolveInfo(
6856                        mInstantAppInstallerInfo);
6857                final ComponentName installFailureActivity = findInstallFailureActivity(
6858                        info.activityInfo.packageName,  filterCallingUid, userId);
6859                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6860                        installFailureActivity,
6861                        info.activityInfo.packageName,
6862                        info.activityInfo.applicationInfo.versionCode,
6863                        info.activityInfo.splitName);
6864                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6865                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6866                // add a non-generic filter
6867                installerInfo.filter = new IntentFilter();
6868
6869                // This resolve info may appear in the chooser UI, so let us make it
6870                // look as the one it replaces as far as the user is concerned which
6871                // requires loading the correct label and icon for the resolve info.
6872                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6873                installerInfo.labelRes = info.resolveLabelResId();
6874                installerInfo.icon = info.resolveIconResId();
6875
6876                // propagate priority/preferred order/default
6877                installerInfo.priority = info.priority;
6878                installerInfo.preferredOrder = info.preferredOrder;
6879                installerInfo.isDefault = info.isDefault;
6880                installerInfo.isInstantAppAvailable = true;
6881                resolveInfos.set(i, installerInfo);
6882                continue;
6883            }
6884            // caller is a full app, don't need to apply any other filtering
6885            if (ephemeralPkgName == null) {
6886                continue;
6887            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
6888                // caller is same app; don't need to apply any other filtering
6889                continue;
6890            }
6891            // allow activities that have been explicitly exposed to ephemeral apps
6892            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6893            if (!isEphemeralApp
6894                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6895                continue;
6896            }
6897            resolveInfos.remove(i);
6898        }
6899        return resolveInfos;
6900    }
6901
6902    /**
6903     * Returns the activity component that can handle install failures.
6904     * <p>By default, the instant application installer handles failures. However, an
6905     * application may want to handle failures on its own. Applications do this by
6906     * creating an activity with an intent filter that handles the action
6907     * {@link Intent#ACTION_INSTALL_FAILURE}.
6908     */
6909    private @Nullable ComponentName findInstallFailureActivity(
6910            String packageName, int filterCallingUid, int userId) {
6911        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
6912        failureActivityIntent.setPackage(packageName);
6913        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
6914        final List<ResolveInfo> result = queryIntentActivitiesInternal(
6915                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
6916                false /*resolveForStart*/, false /*allowDynamicSplits*/);
6917        final int NR = result.size();
6918        if (NR > 0) {
6919            for (int i = 0; i < NR; i++) {
6920                final ResolveInfo info = result.get(i);
6921                if (info.activityInfo.splitName != null) {
6922                    continue;
6923                }
6924                return new ComponentName(packageName, info.activityInfo.name);
6925            }
6926        }
6927        return null;
6928    }
6929
6930    /**
6931     * @param resolveInfos list of resolve infos in descending priority order
6932     * @return if the list contains a resolve info with non-negative priority
6933     */
6934    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6935        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6936    }
6937
6938    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6939            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6940            int userId) {
6941        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6942
6943        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6944            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6945                    candidates.size());
6946        }
6947
6948        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6949        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6950        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6951        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6952        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6953        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6954
6955        synchronized (mPackages) {
6956            final int count = candidates.size();
6957            // First, try to use linked apps. Partition the candidates into four lists:
6958            // one for the final results, one for the "do not use ever", one for "undefined status"
6959            // and finally one for "browser app type".
6960            for (int n=0; n<count; n++) {
6961                ResolveInfo info = candidates.get(n);
6962                String packageName = info.activityInfo.packageName;
6963                PackageSetting ps = mSettings.mPackages.get(packageName);
6964                if (ps != null) {
6965                    // Add to the special match all list (Browser use case)
6966                    if (info.handleAllWebDataURI) {
6967                        matchAllList.add(info);
6968                        continue;
6969                    }
6970                    // Try to get the status from User settings first
6971                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6972                    int status = (int)(packedStatus >> 32);
6973                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6974                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6975                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6976                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6977                                    + " : linkgen=" + linkGeneration);
6978                        }
6979                        // Use link-enabled generation as preferredOrder, i.e.
6980                        // prefer newly-enabled over earlier-enabled.
6981                        info.preferredOrder = linkGeneration;
6982                        alwaysList.add(info);
6983                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6984                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6985                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6986                        }
6987                        neverList.add(info);
6988                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6989                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6990                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6991                        }
6992                        alwaysAskList.add(info);
6993                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6994                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6995                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6996                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6997                        }
6998                        undefinedList.add(info);
6999                    }
7000                }
7001            }
7002
7003            // We'll want to include browser possibilities in a few cases
7004            boolean includeBrowser = false;
7005
7006            // First try to add the "always" resolution(s) for the current user, if any
7007            if (alwaysList.size() > 0) {
7008                result.addAll(alwaysList);
7009            } else {
7010                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7011                result.addAll(undefinedList);
7012                // Maybe add one for the other profile.
7013                if (xpDomainInfo != null && (
7014                        xpDomainInfo.bestDomainVerificationStatus
7015                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7016                    result.add(xpDomainInfo.resolveInfo);
7017                }
7018                includeBrowser = true;
7019            }
7020
7021            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7022            // If there were 'always' entries their preferred order has been set, so we also
7023            // back that off to make the alternatives equivalent
7024            if (alwaysAskList.size() > 0) {
7025                for (ResolveInfo i : result) {
7026                    i.preferredOrder = 0;
7027                }
7028                result.addAll(alwaysAskList);
7029                includeBrowser = true;
7030            }
7031
7032            if (includeBrowser) {
7033                // Also add browsers (all of them or only the default one)
7034                if (DEBUG_DOMAIN_VERIFICATION) {
7035                    Slog.v(TAG, "   ...including browsers in candidate set");
7036                }
7037                if ((matchFlags & MATCH_ALL) != 0) {
7038                    result.addAll(matchAllList);
7039                } else {
7040                    // Browser/generic handling case.  If there's a default browser, go straight
7041                    // to that (but only if there is no other higher-priority match).
7042                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7043                    int maxMatchPrio = 0;
7044                    ResolveInfo defaultBrowserMatch = null;
7045                    final int numCandidates = matchAllList.size();
7046                    for (int n = 0; n < numCandidates; n++) {
7047                        ResolveInfo info = matchAllList.get(n);
7048                        // track the highest overall match priority...
7049                        if (info.priority > maxMatchPrio) {
7050                            maxMatchPrio = info.priority;
7051                        }
7052                        // ...and the highest-priority default browser match
7053                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7054                            if (defaultBrowserMatch == null
7055                                    || (defaultBrowserMatch.priority < info.priority)) {
7056                                if (debug) {
7057                                    Slog.v(TAG, "Considering default browser match " + info);
7058                                }
7059                                defaultBrowserMatch = info;
7060                            }
7061                        }
7062                    }
7063                    if (defaultBrowserMatch != null
7064                            && defaultBrowserMatch.priority >= maxMatchPrio
7065                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7066                    {
7067                        if (debug) {
7068                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7069                        }
7070                        result.add(defaultBrowserMatch);
7071                    } else {
7072                        result.addAll(matchAllList);
7073                    }
7074                }
7075
7076                // If there is nothing selected, add all candidates and remove the ones that the user
7077                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7078                if (result.size() == 0) {
7079                    result.addAll(candidates);
7080                    result.removeAll(neverList);
7081                }
7082            }
7083        }
7084        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7085            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7086                    result.size());
7087            for (ResolveInfo info : result) {
7088                Slog.v(TAG, "  + " + info.activityInfo);
7089            }
7090        }
7091        return result;
7092    }
7093
7094    // Returns a packed value as a long:
7095    //
7096    // high 'int'-sized word: link status: undefined/ask/never/always.
7097    // low 'int'-sized word: relative priority among 'always' results.
7098    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7099        long result = ps.getDomainVerificationStatusForUser(userId);
7100        // if none available, get the master status
7101        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7102            if (ps.getIntentFilterVerificationInfo() != null) {
7103                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7104            }
7105        }
7106        return result;
7107    }
7108
7109    private ResolveInfo querySkipCurrentProfileIntents(
7110            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7111            int flags, int sourceUserId) {
7112        if (matchingFilters != null) {
7113            int size = matchingFilters.size();
7114            for (int i = 0; i < size; i ++) {
7115                CrossProfileIntentFilter filter = matchingFilters.get(i);
7116                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7117                    // Checking if there are activities in the target user that can handle the
7118                    // intent.
7119                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7120                            resolvedType, flags, sourceUserId);
7121                    if (resolveInfo != null) {
7122                        return resolveInfo;
7123                    }
7124                }
7125            }
7126        }
7127        return null;
7128    }
7129
7130    // Return matching ResolveInfo in target user if any.
7131    private ResolveInfo queryCrossProfileIntents(
7132            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7133            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7134        if (matchingFilters != null) {
7135            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7136            // match the same intent. For performance reasons, it is better not to
7137            // run queryIntent twice for the same userId
7138            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7139            int size = matchingFilters.size();
7140            for (int i = 0; i < size; i++) {
7141                CrossProfileIntentFilter filter = matchingFilters.get(i);
7142                int targetUserId = filter.getTargetUserId();
7143                boolean skipCurrentProfile =
7144                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7145                boolean skipCurrentProfileIfNoMatchFound =
7146                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7147                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7148                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7149                    // Checking if there are activities in the target user that can handle the
7150                    // intent.
7151                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7152                            resolvedType, flags, sourceUserId);
7153                    if (resolveInfo != null) return resolveInfo;
7154                    alreadyTriedUserIds.put(targetUserId, true);
7155                }
7156            }
7157        }
7158        return null;
7159    }
7160
7161    /**
7162     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7163     * will forward the intent to the filter's target user.
7164     * Otherwise, returns null.
7165     */
7166    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7167            String resolvedType, int flags, int sourceUserId) {
7168        int targetUserId = filter.getTargetUserId();
7169        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7170                resolvedType, flags, targetUserId);
7171        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7172            // If all the matches in the target profile are suspended, return null.
7173            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7174                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7175                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7176                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7177                            targetUserId);
7178                }
7179            }
7180        }
7181        return null;
7182    }
7183
7184    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7185            int sourceUserId, int targetUserId) {
7186        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7187        long ident = Binder.clearCallingIdentity();
7188        boolean targetIsProfile;
7189        try {
7190            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7191        } finally {
7192            Binder.restoreCallingIdentity(ident);
7193        }
7194        String className;
7195        if (targetIsProfile) {
7196            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7197        } else {
7198            className = FORWARD_INTENT_TO_PARENT;
7199        }
7200        ComponentName forwardingActivityComponentName = new ComponentName(
7201                mAndroidApplication.packageName, className);
7202        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7203                sourceUserId);
7204        if (!targetIsProfile) {
7205            forwardingActivityInfo.showUserIcon = targetUserId;
7206            forwardingResolveInfo.noResourceId = true;
7207        }
7208        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7209        forwardingResolveInfo.priority = 0;
7210        forwardingResolveInfo.preferredOrder = 0;
7211        forwardingResolveInfo.match = 0;
7212        forwardingResolveInfo.isDefault = true;
7213        forwardingResolveInfo.filter = filter;
7214        forwardingResolveInfo.targetUserId = targetUserId;
7215        return forwardingResolveInfo;
7216    }
7217
7218    @Override
7219    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7220            Intent[] specifics, String[] specificTypes, Intent intent,
7221            String resolvedType, int flags, int userId) {
7222        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7223                specificTypes, intent, resolvedType, flags, userId));
7224    }
7225
7226    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7227            Intent[] specifics, String[] specificTypes, Intent intent,
7228            String resolvedType, int flags, int userId) {
7229        if (!sUserManager.exists(userId)) return Collections.emptyList();
7230        final int callingUid = Binder.getCallingUid();
7231        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7232                false /*includeInstantApps*/);
7233        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7234                false /*requireFullPermission*/, false /*checkShell*/,
7235                "query intent activity options");
7236        final String resultsAction = intent.getAction();
7237
7238        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7239                | PackageManager.GET_RESOLVED_FILTER, userId);
7240
7241        if (DEBUG_INTENT_MATCHING) {
7242            Log.v(TAG, "Query " + intent + ": " + results);
7243        }
7244
7245        int specificsPos = 0;
7246        int N;
7247
7248        // todo: note that the algorithm used here is O(N^2).  This
7249        // isn't a problem in our current environment, but if we start running
7250        // into situations where we have more than 5 or 10 matches then this
7251        // should probably be changed to something smarter...
7252
7253        // First we go through and resolve each of the specific items
7254        // that were supplied, taking care of removing any corresponding
7255        // duplicate items in the generic resolve list.
7256        if (specifics != null) {
7257            for (int i=0; i<specifics.length; i++) {
7258                final Intent sintent = specifics[i];
7259                if (sintent == null) {
7260                    continue;
7261                }
7262
7263                if (DEBUG_INTENT_MATCHING) {
7264                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7265                }
7266
7267                String action = sintent.getAction();
7268                if (resultsAction != null && resultsAction.equals(action)) {
7269                    // If this action was explicitly requested, then don't
7270                    // remove things that have it.
7271                    action = null;
7272                }
7273
7274                ResolveInfo ri = null;
7275                ActivityInfo ai = null;
7276
7277                ComponentName comp = sintent.getComponent();
7278                if (comp == null) {
7279                    ri = resolveIntent(
7280                        sintent,
7281                        specificTypes != null ? specificTypes[i] : null,
7282                            flags, userId);
7283                    if (ri == null) {
7284                        continue;
7285                    }
7286                    if (ri == mResolveInfo) {
7287                        // ACK!  Must do something better with this.
7288                    }
7289                    ai = ri.activityInfo;
7290                    comp = new ComponentName(ai.applicationInfo.packageName,
7291                            ai.name);
7292                } else {
7293                    ai = getActivityInfo(comp, flags, userId);
7294                    if (ai == null) {
7295                        continue;
7296                    }
7297                }
7298
7299                // Look for any generic query activities that are duplicates
7300                // of this specific one, and remove them from the results.
7301                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7302                N = results.size();
7303                int j;
7304                for (j=specificsPos; j<N; j++) {
7305                    ResolveInfo sri = results.get(j);
7306                    if ((sri.activityInfo.name.equals(comp.getClassName())
7307                            && sri.activityInfo.applicationInfo.packageName.equals(
7308                                    comp.getPackageName()))
7309                        || (action != null && sri.filter.matchAction(action))) {
7310                        results.remove(j);
7311                        if (DEBUG_INTENT_MATCHING) Log.v(
7312                            TAG, "Removing duplicate item from " + j
7313                            + " due to specific " + specificsPos);
7314                        if (ri == null) {
7315                            ri = sri;
7316                        }
7317                        j--;
7318                        N--;
7319                    }
7320                }
7321
7322                // Add this specific item to its proper place.
7323                if (ri == null) {
7324                    ri = new ResolveInfo();
7325                    ri.activityInfo = ai;
7326                }
7327                results.add(specificsPos, ri);
7328                ri.specificIndex = i;
7329                specificsPos++;
7330            }
7331        }
7332
7333        // Now we go through the remaining generic results and remove any
7334        // duplicate actions that are found here.
7335        N = results.size();
7336        for (int i=specificsPos; i<N-1; i++) {
7337            final ResolveInfo rii = results.get(i);
7338            if (rii.filter == null) {
7339                continue;
7340            }
7341
7342            // Iterate over all of the actions of this result's intent
7343            // filter...  typically this should be just one.
7344            final Iterator<String> it = rii.filter.actionsIterator();
7345            if (it == null) {
7346                continue;
7347            }
7348            while (it.hasNext()) {
7349                final String action = it.next();
7350                if (resultsAction != null && resultsAction.equals(action)) {
7351                    // If this action was explicitly requested, then don't
7352                    // remove things that have it.
7353                    continue;
7354                }
7355                for (int j=i+1; j<N; j++) {
7356                    final ResolveInfo rij = results.get(j);
7357                    if (rij.filter != null && rij.filter.hasAction(action)) {
7358                        results.remove(j);
7359                        if (DEBUG_INTENT_MATCHING) Log.v(
7360                            TAG, "Removing duplicate item from " + j
7361                            + " due to action " + action + " at " + i);
7362                        j--;
7363                        N--;
7364                    }
7365                }
7366            }
7367
7368            // If the caller didn't request filter information, drop it now
7369            // so we don't have to marshall/unmarshall it.
7370            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7371                rii.filter = null;
7372            }
7373        }
7374
7375        // Filter out the caller activity if so requested.
7376        if (caller != null) {
7377            N = results.size();
7378            for (int i=0; i<N; i++) {
7379                ActivityInfo ainfo = results.get(i).activityInfo;
7380                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7381                        && caller.getClassName().equals(ainfo.name)) {
7382                    results.remove(i);
7383                    break;
7384                }
7385            }
7386        }
7387
7388        // If the caller didn't request filter information,
7389        // drop them now so we don't have to
7390        // marshall/unmarshall it.
7391        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7392            N = results.size();
7393            for (int i=0; i<N; i++) {
7394                results.get(i).filter = null;
7395            }
7396        }
7397
7398        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7399        return results;
7400    }
7401
7402    @Override
7403    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7404            String resolvedType, int flags, int userId) {
7405        return new ParceledListSlice<>(
7406                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7407                        false /*allowDynamicSplits*/));
7408    }
7409
7410    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7411            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7412        if (!sUserManager.exists(userId)) return Collections.emptyList();
7413        final int callingUid = Binder.getCallingUid();
7414        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7415                false /*requireFullPermission*/, false /*checkShell*/,
7416                "query intent receivers");
7417        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7418        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7419                false /*includeInstantApps*/);
7420        ComponentName comp = intent.getComponent();
7421        if (comp == null) {
7422            if (intent.getSelector() != null) {
7423                intent = intent.getSelector();
7424                comp = intent.getComponent();
7425            }
7426        }
7427        if (comp != null) {
7428            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7429            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7430            if (ai != null) {
7431                // When specifying an explicit component, we prevent the activity from being
7432                // used when either 1) the calling package is normal and the activity is within
7433                // an instant application or 2) the calling package is ephemeral and the
7434                // activity is not visible to instant applications.
7435                final boolean matchInstantApp =
7436                        (flags & PackageManager.MATCH_INSTANT) != 0;
7437                final boolean matchVisibleToInstantAppOnly =
7438                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7439                final boolean matchExplicitlyVisibleOnly =
7440                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7441                final boolean isCallerInstantApp =
7442                        instantAppPkgName != null;
7443                final boolean isTargetSameInstantApp =
7444                        comp.getPackageName().equals(instantAppPkgName);
7445                final boolean isTargetInstantApp =
7446                        (ai.applicationInfo.privateFlags
7447                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7448                final boolean isTargetVisibleToInstantApp =
7449                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7450                final boolean isTargetExplicitlyVisibleToInstantApp =
7451                        isTargetVisibleToInstantApp
7452                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7453                final boolean isTargetHiddenFromInstantApp =
7454                        !isTargetVisibleToInstantApp
7455                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7456                final boolean blockResolution =
7457                        !isTargetSameInstantApp
7458                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7459                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7460                                        && isTargetHiddenFromInstantApp));
7461                if (!blockResolution) {
7462                    ResolveInfo ri = new ResolveInfo();
7463                    ri.activityInfo = ai;
7464                    list.add(ri);
7465                }
7466            }
7467            return applyPostResolutionFilter(
7468                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7469        }
7470
7471        // reader
7472        synchronized (mPackages) {
7473            String pkgName = intent.getPackage();
7474            if (pkgName == null) {
7475                final List<ResolveInfo> result =
7476                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7477                return applyPostResolutionFilter(
7478                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7479            }
7480            final PackageParser.Package pkg = mPackages.get(pkgName);
7481            if (pkg != null) {
7482                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7483                        intent, resolvedType, flags, pkg.receivers, userId);
7484                return applyPostResolutionFilter(
7485                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7486            }
7487            return Collections.emptyList();
7488        }
7489    }
7490
7491    @Override
7492    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7493        final int callingUid = Binder.getCallingUid();
7494        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7495    }
7496
7497    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7498            int userId, int callingUid) {
7499        if (!sUserManager.exists(userId)) return null;
7500        flags = updateFlagsForResolve(
7501                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7502        List<ResolveInfo> query = queryIntentServicesInternal(
7503                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7504        if (query != null) {
7505            if (query.size() >= 1) {
7506                // If there is more than one service with the same priority,
7507                // just arbitrarily pick the first one.
7508                return query.get(0);
7509            }
7510        }
7511        return null;
7512    }
7513
7514    @Override
7515    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7516            String resolvedType, int flags, int userId) {
7517        final int callingUid = Binder.getCallingUid();
7518        return new ParceledListSlice<>(queryIntentServicesInternal(
7519                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7520    }
7521
7522    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7523            String resolvedType, int flags, int userId, int callingUid,
7524            boolean includeInstantApps) {
7525        if (!sUserManager.exists(userId)) return Collections.emptyList();
7526        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7527                false /*requireFullPermission*/, false /*checkShell*/,
7528                "query intent receivers");
7529        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7530        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7531        ComponentName comp = intent.getComponent();
7532        if (comp == null) {
7533            if (intent.getSelector() != null) {
7534                intent = intent.getSelector();
7535                comp = intent.getComponent();
7536            }
7537        }
7538        if (comp != null) {
7539            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7540            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7541            if (si != null) {
7542                // When specifying an explicit component, we prevent the service from being
7543                // used when either 1) the service is in an instant application and the
7544                // caller is not the same instant application or 2) the calling package is
7545                // ephemeral and the activity is not visible to ephemeral applications.
7546                final boolean matchInstantApp =
7547                        (flags & PackageManager.MATCH_INSTANT) != 0;
7548                final boolean matchVisibleToInstantAppOnly =
7549                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7550                final boolean isCallerInstantApp =
7551                        instantAppPkgName != null;
7552                final boolean isTargetSameInstantApp =
7553                        comp.getPackageName().equals(instantAppPkgName);
7554                final boolean isTargetInstantApp =
7555                        (si.applicationInfo.privateFlags
7556                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7557                final boolean isTargetHiddenFromInstantApp =
7558                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7559                final boolean blockResolution =
7560                        !isTargetSameInstantApp
7561                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7562                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7563                                        && isTargetHiddenFromInstantApp));
7564                if (!blockResolution) {
7565                    final ResolveInfo ri = new ResolveInfo();
7566                    ri.serviceInfo = si;
7567                    list.add(ri);
7568                }
7569            }
7570            return list;
7571        }
7572
7573        // reader
7574        synchronized (mPackages) {
7575            String pkgName = intent.getPackage();
7576            if (pkgName == null) {
7577                return applyPostServiceResolutionFilter(
7578                        mServices.queryIntent(intent, resolvedType, flags, userId),
7579                        instantAppPkgName);
7580            }
7581            final PackageParser.Package pkg = mPackages.get(pkgName);
7582            if (pkg != null) {
7583                return applyPostServiceResolutionFilter(
7584                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7585                                userId),
7586                        instantAppPkgName);
7587            }
7588            return Collections.emptyList();
7589        }
7590    }
7591
7592    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7593            String instantAppPkgName) {
7594        if (instantAppPkgName == null) {
7595            return resolveInfos;
7596        }
7597        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7598            final ResolveInfo info = resolveInfos.get(i);
7599            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7600            // allow services that are defined in the provided package
7601            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7602                if (info.serviceInfo.splitName != null
7603                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7604                                info.serviceInfo.splitName)) {
7605                    // requested service is defined in a split that hasn't been installed yet.
7606                    // add the installer to the resolve list
7607                    if (DEBUG_EPHEMERAL) {
7608                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7609                    }
7610                    final ResolveInfo installerInfo = new ResolveInfo(
7611                            mInstantAppInstallerInfo);
7612                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7613                            null /* installFailureActivity */,
7614                            info.serviceInfo.packageName,
7615                            info.serviceInfo.applicationInfo.versionCode,
7616                            info.serviceInfo.splitName);
7617                    // make sure this resolver is the default
7618                    installerInfo.isDefault = true;
7619                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7620                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7621                    // add a non-generic filter
7622                    installerInfo.filter = new IntentFilter();
7623                    // load resources from the correct package
7624                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7625                    resolveInfos.set(i, installerInfo);
7626                }
7627                continue;
7628            }
7629            // allow services that have been explicitly exposed to ephemeral apps
7630            if (!isEphemeralApp
7631                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7632                continue;
7633            }
7634            resolveInfos.remove(i);
7635        }
7636        return resolveInfos;
7637    }
7638
7639    @Override
7640    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7641            String resolvedType, int flags, int userId) {
7642        return new ParceledListSlice<>(
7643                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7644    }
7645
7646    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7647            Intent intent, String resolvedType, int flags, int userId) {
7648        if (!sUserManager.exists(userId)) return Collections.emptyList();
7649        final int callingUid = Binder.getCallingUid();
7650        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7651        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7652                false /*includeInstantApps*/);
7653        ComponentName comp = intent.getComponent();
7654        if (comp == null) {
7655            if (intent.getSelector() != null) {
7656                intent = intent.getSelector();
7657                comp = intent.getComponent();
7658            }
7659        }
7660        if (comp != null) {
7661            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7662            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7663            if (pi != null) {
7664                // When specifying an explicit component, we prevent the provider from being
7665                // used when either 1) the provider is in an instant application and the
7666                // caller is not the same instant application or 2) the calling package is an
7667                // instant application and the provider is not visible to instant applications.
7668                final boolean matchInstantApp =
7669                        (flags & PackageManager.MATCH_INSTANT) != 0;
7670                final boolean matchVisibleToInstantAppOnly =
7671                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7672                final boolean isCallerInstantApp =
7673                        instantAppPkgName != null;
7674                final boolean isTargetSameInstantApp =
7675                        comp.getPackageName().equals(instantAppPkgName);
7676                final boolean isTargetInstantApp =
7677                        (pi.applicationInfo.privateFlags
7678                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7679                final boolean isTargetHiddenFromInstantApp =
7680                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7681                final boolean blockResolution =
7682                        !isTargetSameInstantApp
7683                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7684                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7685                                        && isTargetHiddenFromInstantApp));
7686                if (!blockResolution) {
7687                    final ResolveInfo ri = new ResolveInfo();
7688                    ri.providerInfo = pi;
7689                    list.add(ri);
7690                }
7691            }
7692            return list;
7693        }
7694
7695        // reader
7696        synchronized (mPackages) {
7697            String pkgName = intent.getPackage();
7698            if (pkgName == null) {
7699                return applyPostContentProviderResolutionFilter(
7700                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7701                        instantAppPkgName);
7702            }
7703            final PackageParser.Package pkg = mPackages.get(pkgName);
7704            if (pkg != null) {
7705                return applyPostContentProviderResolutionFilter(
7706                        mProviders.queryIntentForPackage(
7707                        intent, resolvedType, flags, pkg.providers, userId),
7708                        instantAppPkgName);
7709            }
7710            return Collections.emptyList();
7711        }
7712    }
7713
7714    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7715            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7716        if (instantAppPkgName == null) {
7717            return resolveInfos;
7718        }
7719        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7720            final ResolveInfo info = resolveInfos.get(i);
7721            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7722            // allow providers that are defined in the provided package
7723            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7724                if (info.providerInfo.splitName != null
7725                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7726                                info.providerInfo.splitName)) {
7727                    // requested provider is defined in a split that hasn't been installed yet.
7728                    // add the installer to the resolve list
7729                    if (DEBUG_EPHEMERAL) {
7730                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7731                    }
7732                    final ResolveInfo installerInfo = new ResolveInfo(
7733                            mInstantAppInstallerInfo);
7734                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7735                            null /*failureActivity*/,
7736                            info.providerInfo.packageName,
7737                            info.providerInfo.applicationInfo.versionCode,
7738                            info.providerInfo.splitName);
7739                    // make sure this resolver is the default
7740                    installerInfo.isDefault = true;
7741                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7742                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7743                    // add a non-generic filter
7744                    installerInfo.filter = new IntentFilter();
7745                    // load resources from the correct package
7746                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7747                    resolveInfos.set(i, installerInfo);
7748                }
7749                continue;
7750            }
7751            // allow providers that have been explicitly exposed to instant applications
7752            if (!isEphemeralApp
7753                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7754                continue;
7755            }
7756            resolveInfos.remove(i);
7757        }
7758        return resolveInfos;
7759    }
7760
7761    @Override
7762    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7763        final int callingUid = Binder.getCallingUid();
7764        if (getInstantAppPackageName(callingUid) != null) {
7765            return ParceledListSlice.emptyList();
7766        }
7767        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7768        flags = updateFlagsForPackage(flags, userId, null);
7769        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7770        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7771                true /* requireFullPermission */, false /* checkShell */,
7772                "get installed packages");
7773
7774        // writer
7775        synchronized (mPackages) {
7776            ArrayList<PackageInfo> list;
7777            if (listUninstalled) {
7778                list = new ArrayList<>(mSettings.mPackages.size());
7779                for (PackageSetting ps : mSettings.mPackages.values()) {
7780                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7781                        continue;
7782                    }
7783                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7784                        continue;
7785                    }
7786                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7787                    if (pi != null) {
7788                        list.add(pi);
7789                    }
7790                }
7791            } else {
7792                list = new ArrayList<>(mPackages.size());
7793                for (PackageParser.Package p : mPackages.values()) {
7794                    final PackageSetting ps = (PackageSetting) p.mExtras;
7795                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7796                        continue;
7797                    }
7798                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7799                        continue;
7800                    }
7801                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7802                            p.mExtras, flags, userId);
7803                    if (pi != null) {
7804                        list.add(pi);
7805                    }
7806                }
7807            }
7808
7809            return new ParceledListSlice<>(list);
7810        }
7811    }
7812
7813    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7814            String[] permissions, boolean[] tmp, int flags, int userId) {
7815        int numMatch = 0;
7816        final PermissionsState permissionsState = ps.getPermissionsState();
7817        for (int i=0; i<permissions.length; i++) {
7818            final String permission = permissions[i];
7819            if (permissionsState.hasPermission(permission, userId)) {
7820                tmp[i] = true;
7821                numMatch++;
7822            } else {
7823                tmp[i] = false;
7824            }
7825        }
7826        if (numMatch == 0) {
7827            return;
7828        }
7829        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7830
7831        // The above might return null in cases of uninstalled apps or install-state
7832        // skew across users/profiles.
7833        if (pi != null) {
7834            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7835                if (numMatch == permissions.length) {
7836                    pi.requestedPermissions = permissions;
7837                } else {
7838                    pi.requestedPermissions = new String[numMatch];
7839                    numMatch = 0;
7840                    for (int i=0; i<permissions.length; i++) {
7841                        if (tmp[i]) {
7842                            pi.requestedPermissions[numMatch] = permissions[i];
7843                            numMatch++;
7844                        }
7845                    }
7846                }
7847            }
7848            list.add(pi);
7849        }
7850    }
7851
7852    @Override
7853    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7854            String[] permissions, int flags, int userId) {
7855        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7856        flags = updateFlagsForPackage(flags, userId, permissions);
7857        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7858                true /* requireFullPermission */, false /* checkShell */,
7859                "get packages holding permissions");
7860        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7861
7862        // writer
7863        synchronized (mPackages) {
7864            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7865            boolean[] tmpBools = new boolean[permissions.length];
7866            if (listUninstalled) {
7867                for (PackageSetting ps : mSettings.mPackages.values()) {
7868                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7869                            userId);
7870                }
7871            } else {
7872                for (PackageParser.Package pkg : mPackages.values()) {
7873                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7874                    if (ps != null) {
7875                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7876                                userId);
7877                    }
7878                }
7879            }
7880
7881            return new ParceledListSlice<PackageInfo>(list);
7882        }
7883    }
7884
7885    @Override
7886    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7887        final int callingUid = Binder.getCallingUid();
7888        if (getInstantAppPackageName(callingUid) != null) {
7889            return ParceledListSlice.emptyList();
7890        }
7891        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7892        flags = updateFlagsForApplication(flags, userId, null);
7893        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7894
7895        // writer
7896        synchronized (mPackages) {
7897            ArrayList<ApplicationInfo> list;
7898            if (listUninstalled) {
7899                list = new ArrayList<>(mSettings.mPackages.size());
7900                for (PackageSetting ps : mSettings.mPackages.values()) {
7901                    ApplicationInfo ai;
7902                    int effectiveFlags = flags;
7903                    if (ps.isSystem()) {
7904                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7905                    }
7906                    if (ps.pkg != null) {
7907                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7908                            continue;
7909                        }
7910                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7911                            continue;
7912                        }
7913                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7914                                ps.readUserState(userId), userId);
7915                        if (ai != null) {
7916                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7917                        }
7918                    } else {
7919                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7920                        // and already converts to externally visible package name
7921                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7922                                callingUid, effectiveFlags, userId);
7923                    }
7924                    if (ai != null) {
7925                        list.add(ai);
7926                    }
7927                }
7928            } else {
7929                list = new ArrayList<>(mPackages.size());
7930                for (PackageParser.Package p : mPackages.values()) {
7931                    if (p.mExtras != null) {
7932                        PackageSetting ps = (PackageSetting) p.mExtras;
7933                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
7934                            continue;
7935                        }
7936                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7937                            continue;
7938                        }
7939                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7940                                ps.readUserState(userId), userId);
7941                        if (ai != null) {
7942                            ai.packageName = resolveExternalPackageNameLPr(p);
7943                            list.add(ai);
7944                        }
7945                    }
7946                }
7947            }
7948
7949            return new ParceledListSlice<>(list);
7950        }
7951    }
7952
7953    @Override
7954    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7955        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7956            return null;
7957        }
7958        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
7959            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7960                    "getEphemeralApplications");
7961        }
7962        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7963                true /* requireFullPermission */, false /* checkShell */,
7964                "getEphemeralApplications");
7965        synchronized (mPackages) {
7966            List<InstantAppInfo> instantApps = mInstantAppRegistry
7967                    .getInstantAppsLPr(userId);
7968            if (instantApps != null) {
7969                return new ParceledListSlice<>(instantApps);
7970            }
7971        }
7972        return null;
7973    }
7974
7975    @Override
7976    public boolean isInstantApp(String packageName, int userId) {
7977        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7978                true /* requireFullPermission */, false /* checkShell */,
7979                "isInstantApp");
7980        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7981            return false;
7982        }
7983
7984        synchronized (mPackages) {
7985            int callingUid = Binder.getCallingUid();
7986            if (Process.isIsolated(callingUid)) {
7987                callingUid = mIsolatedOwners.get(callingUid);
7988            }
7989            final PackageSetting ps = mSettings.mPackages.get(packageName);
7990            PackageParser.Package pkg = mPackages.get(packageName);
7991            final boolean returnAllowed =
7992                    ps != null
7993                    && (isCallerSameApp(packageName, callingUid)
7994                            || canViewInstantApps(callingUid, userId)
7995                            || mInstantAppRegistry.isInstantAccessGranted(
7996                                    userId, UserHandle.getAppId(callingUid), ps.appId));
7997            if (returnAllowed) {
7998                return ps.getInstantApp(userId);
7999            }
8000        }
8001        return false;
8002    }
8003
8004    @Override
8005    public byte[] getInstantAppCookie(String packageName, int userId) {
8006        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8007            return null;
8008        }
8009
8010        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8011                true /* requireFullPermission */, false /* checkShell */,
8012                "getInstantAppCookie");
8013        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8014            return null;
8015        }
8016        synchronized (mPackages) {
8017            return mInstantAppRegistry.getInstantAppCookieLPw(
8018                    packageName, userId);
8019        }
8020    }
8021
8022    @Override
8023    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8024        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8025            return true;
8026        }
8027
8028        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8029                true /* requireFullPermission */, true /* checkShell */,
8030                "setInstantAppCookie");
8031        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8032            return false;
8033        }
8034        synchronized (mPackages) {
8035            return mInstantAppRegistry.setInstantAppCookieLPw(
8036                    packageName, cookie, userId);
8037        }
8038    }
8039
8040    @Override
8041    public Bitmap getInstantAppIcon(String packageName, int userId) {
8042        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8043            return null;
8044        }
8045
8046        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8047            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8048                    "getInstantAppIcon");
8049        }
8050        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8051                true /* requireFullPermission */, false /* checkShell */,
8052                "getInstantAppIcon");
8053
8054        synchronized (mPackages) {
8055            return mInstantAppRegistry.getInstantAppIconLPw(
8056                    packageName, userId);
8057        }
8058    }
8059
8060    private boolean isCallerSameApp(String packageName, int uid) {
8061        PackageParser.Package pkg = mPackages.get(packageName);
8062        return pkg != null
8063                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8064    }
8065
8066    @Override
8067    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8068        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8069            return ParceledListSlice.emptyList();
8070        }
8071        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8072    }
8073
8074    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8075        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8076
8077        // reader
8078        synchronized (mPackages) {
8079            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8080            final int userId = UserHandle.getCallingUserId();
8081            while (i.hasNext()) {
8082                final PackageParser.Package p = i.next();
8083                if (p.applicationInfo == null) continue;
8084
8085                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8086                        && !p.applicationInfo.isDirectBootAware();
8087                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8088                        && p.applicationInfo.isDirectBootAware();
8089
8090                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8091                        && (!mSafeMode || isSystemApp(p))
8092                        && (matchesUnaware || matchesAware)) {
8093                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8094                    if (ps != null) {
8095                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8096                                ps.readUserState(userId), userId);
8097                        if (ai != null) {
8098                            finalList.add(ai);
8099                        }
8100                    }
8101                }
8102            }
8103        }
8104
8105        return finalList;
8106    }
8107
8108    @Override
8109    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8110        return resolveContentProviderInternal(name, flags, userId);
8111    }
8112
8113    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
8114        if (!sUserManager.exists(userId)) return null;
8115        flags = updateFlagsForComponent(flags, userId, name);
8116        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8117        // reader
8118        synchronized (mPackages) {
8119            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8120            PackageSetting ps = provider != null
8121                    ? mSettings.mPackages.get(provider.owner.packageName)
8122                    : null;
8123            if (ps != null) {
8124                final boolean isInstantApp = ps.getInstantApp(userId);
8125                // normal application; filter out instant application provider
8126                if (instantAppPkgName == null && isInstantApp) {
8127                    return null;
8128                }
8129                // instant application; filter out other instant applications
8130                if (instantAppPkgName != null
8131                        && isInstantApp
8132                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8133                    return null;
8134                }
8135                // instant application; filter out non-exposed provider
8136                if (instantAppPkgName != null
8137                        && !isInstantApp
8138                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8139                    return null;
8140                }
8141                // provider not enabled
8142                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8143                    return null;
8144                }
8145                return PackageParser.generateProviderInfo(
8146                        provider, flags, ps.readUserState(userId), userId);
8147            }
8148            return null;
8149        }
8150    }
8151
8152    /**
8153     * @deprecated
8154     */
8155    @Deprecated
8156    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8157        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8158            return;
8159        }
8160        // reader
8161        synchronized (mPackages) {
8162            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8163                    .entrySet().iterator();
8164            final int userId = UserHandle.getCallingUserId();
8165            while (i.hasNext()) {
8166                Map.Entry<String, PackageParser.Provider> entry = i.next();
8167                PackageParser.Provider p = entry.getValue();
8168                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8169
8170                if (ps != null && p.syncable
8171                        && (!mSafeMode || (p.info.applicationInfo.flags
8172                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8173                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8174                            ps.readUserState(userId), userId);
8175                    if (info != null) {
8176                        outNames.add(entry.getKey());
8177                        outInfo.add(info);
8178                    }
8179                }
8180            }
8181        }
8182    }
8183
8184    @Override
8185    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8186            int uid, int flags, String metaDataKey) {
8187        final int callingUid = Binder.getCallingUid();
8188        final int userId = processName != null ? UserHandle.getUserId(uid)
8189                : UserHandle.getCallingUserId();
8190        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8191        flags = updateFlagsForComponent(flags, userId, processName);
8192        ArrayList<ProviderInfo> finalList = null;
8193        // reader
8194        synchronized (mPackages) {
8195            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8196            while (i.hasNext()) {
8197                final PackageParser.Provider p = i.next();
8198                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8199                if (ps != null && p.info.authority != null
8200                        && (processName == null
8201                                || (p.info.processName.equals(processName)
8202                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8203                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8204
8205                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8206                    // parameter.
8207                    if (metaDataKey != null
8208                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8209                        continue;
8210                    }
8211                    final ComponentName component =
8212                            new ComponentName(p.info.packageName, p.info.name);
8213                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8214                        continue;
8215                    }
8216                    if (finalList == null) {
8217                        finalList = new ArrayList<ProviderInfo>(3);
8218                    }
8219                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8220                            ps.readUserState(userId), userId);
8221                    if (info != null) {
8222                        finalList.add(info);
8223                    }
8224                }
8225            }
8226        }
8227
8228        if (finalList != null) {
8229            Collections.sort(finalList, mProviderInitOrderSorter);
8230            return new ParceledListSlice<ProviderInfo>(finalList);
8231        }
8232
8233        return ParceledListSlice.emptyList();
8234    }
8235
8236    @Override
8237    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8238        // reader
8239        synchronized (mPackages) {
8240            final int callingUid = Binder.getCallingUid();
8241            final int callingUserId = UserHandle.getUserId(callingUid);
8242            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8243            if (ps == null) return null;
8244            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8245                return null;
8246            }
8247            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8248            return PackageParser.generateInstrumentationInfo(i, flags);
8249        }
8250    }
8251
8252    @Override
8253    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8254            String targetPackage, int flags) {
8255        final int callingUid = Binder.getCallingUid();
8256        final int callingUserId = UserHandle.getUserId(callingUid);
8257        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8258        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8259            return ParceledListSlice.emptyList();
8260        }
8261        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8262    }
8263
8264    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8265            int flags) {
8266        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8267
8268        // reader
8269        synchronized (mPackages) {
8270            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8271            while (i.hasNext()) {
8272                final PackageParser.Instrumentation p = i.next();
8273                if (targetPackage == null
8274                        || targetPackage.equals(p.info.targetPackage)) {
8275                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8276                            flags);
8277                    if (ii != null) {
8278                        finalList.add(ii);
8279                    }
8280                }
8281            }
8282        }
8283
8284        return finalList;
8285    }
8286
8287    private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) {
8288        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]");
8289        try {
8290            scanDirLI(scanDir, parseFlags, scanFlags, currentTime);
8291        } finally {
8292            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8293        }
8294    }
8295
8296    private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) {
8297        final File[] files = scanDir.listFiles();
8298        if (ArrayUtils.isEmpty(files)) {
8299            Log.d(TAG, "No files in app dir " + scanDir);
8300            return;
8301        }
8302
8303        if (DEBUG_PACKAGE_SCANNING) {
8304            Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags
8305                    + " flags=0x" + Integer.toHexString(parseFlags));
8306        }
8307        try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8308                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8309                mParallelPackageParserCallback)) {
8310            // Submit files for parsing in parallel
8311            int fileCount = 0;
8312            for (File file : files) {
8313                final boolean isPackage = (isApkFile(file) || file.isDirectory())
8314                        && !PackageInstallerService.isStageName(file.getName());
8315                if (!isPackage) {
8316                    // Ignore entries which are not packages
8317                    continue;
8318                }
8319                parallelPackageParser.submit(file, parseFlags);
8320                fileCount++;
8321            }
8322
8323            // Process results one by one
8324            for (; fileCount > 0; fileCount--) {
8325                ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8326                Throwable throwable = parseResult.throwable;
8327                int errorCode = PackageManager.INSTALL_SUCCEEDED;
8328
8329                if (throwable == null) {
8330                    // TODO(toddke): move lower in the scan chain
8331                    // Static shared libraries have synthetic package names
8332                    if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8333                        renameStaticSharedLibraryPackage(parseResult.pkg);
8334                    }
8335                    try {
8336                        if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8337                            scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags,
8338                                    currentTime, null);
8339                        }
8340                    } catch (PackageManagerException e) {
8341                        errorCode = e.error;
8342                        Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8343                    }
8344                } else if (throwable instanceof PackageParser.PackageParserException) {
8345                    PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8346                            throwable;
8347                    errorCode = e.error;
8348                    Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8349                } else {
8350                    throw new IllegalStateException("Unexpected exception occurred while parsing "
8351                            + parseResult.scanFile, throwable);
8352                }
8353
8354                // Delete invalid userdata apps
8355                if ((scanFlags & SCAN_AS_SYSTEM) == 0 &&
8356                        errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8357                    logCriticalInfo(Log.WARN,
8358                            "Deleting invalid package at " + parseResult.scanFile);
8359                    removeCodePathLI(parseResult.scanFile);
8360                }
8361            }
8362        }
8363    }
8364
8365    public static void reportSettingsProblem(int priority, String msg) {
8366        logCriticalInfo(priority, msg);
8367    }
8368
8369    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg,
8370            boolean forceCollect) throws PackageManagerException {
8371        // When upgrading from pre-N MR1, verify the package time stamp using the package
8372        // directory and not the APK file.
8373        final long lastModifiedTime = mIsPreNMR1Upgrade
8374                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg);
8375        // Note that currently skipVerify skips verification on both base and splits for simplicity.
8376        final boolean skipVerify = forceCollect && canSkipFullPackageVerification(pkg);
8377        if (ps != null && !forceCollect
8378                && ps.codePathString.equals(pkg.codePath)
8379                && ps.timeStamp == lastModifiedTime
8380                && !isCompatSignatureUpdateNeeded(pkg)
8381                && !isRecoverSignatureUpdateNeeded(pkg)) {
8382            if (ps.signatures.mSigningDetails.signatures != null
8383                    && ps.signatures.mSigningDetails.signatures.length != 0
8384                    && ps.signatures.mSigningDetails.signatureSchemeVersion
8385                            != SignatureSchemeVersion.UNKNOWN) {
8386                // Optimization: reuse the existing cached signing data
8387                // if the package appears to be unchanged.
8388                pkg.mSigningDetails =
8389                        new PackageParser.SigningDetails(ps.signatures.mSigningDetails);
8390                return;
8391            }
8392
8393            Slog.w(TAG, "PackageSetting for " + ps.name
8394                    + " is missing signatures.  Collecting certs again to recover them.");
8395        } else {
8396            Slog.i(TAG, pkg.codePath + " changed; collecting certs" +
8397                    (forceCollect ? " (forced)" : ""));
8398        }
8399
8400        try {
8401            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8402            PackageParser.collectCertificates(pkg, skipVerify);
8403        } catch (PackageParserException e) {
8404            throw PackageManagerException.from(e);
8405        } finally {
8406            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8407        }
8408    }
8409
8410    /**
8411     *  Traces a package scan.
8412     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8413     */
8414    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8415            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8416        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8417        try {
8418            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8419        } finally {
8420            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8421        }
8422    }
8423
8424    /**
8425     *  Scans a package and returns the newly parsed package.
8426     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8427     */
8428    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8429            long currentTime, UserHandle user) throws PackageManagerException {
8430        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8431        PackageParser pp = new PackageParser();
8432        pp.setSeparateProcesses(mSeparateProcesses);
8433        pp.setOnlyCoreApps(mOnlyCore);
8434        pp.setDisplayMetrics(mMetrics);
8435        pp.setCallback(mPackageParserCallback);
8436
8437        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8438        final PackageParser.Package pkg;
8439        try {
8440            pkg = pp.parsePackage(scanFile, parseFlags);
8441        } catch (PackageParserException e) {
8442            throw PackageManagerException.from(e);
8443        } finally {
8444            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8445        }
8446
8447        // Static shared libraries have synthetic package names
8448        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8449            renameStaticSharedLibraryPackage(pkg);
8450        }
8451
8452        return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8453    }
8454
8455    /**
8456     *  Scans a package and returns the newly parsed package.
8457     *  @throws PackageManagerException on a parse error.
8458     */
8459    private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg,
8460            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8461            @Nullable UserHandle user)
8462                    throws PackageManagerException {
8463        // If the package has children and this is the first dive in the function
8464        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8465        // packages (parent and children) would be successfully scanned before the
8466        // actual scan since scanning mutates internal state and we want to atomically
8467        // install the package and its children.
8468        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8469            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8470                scanFlags |= SCAN_CHECK_ONLY;
8471            }
8472        } else {
8473            scanFlags &= ~SCAN_CHECK_ONLY;
8474        }
8475
8476        // Scan the parent
8477        PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags,
8478                scanFlags, currentTime, user);
8479
8480        // Scan the children
8481        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8482        for (int i = 0; i < childCount; i++) {
8483            PackageParser.Package childPackage = pkg.childPackages.get(i);
8484            addForInitLI(childPackage, parseFlags, scanFlags,
8485                    currentTime, user);
8486        }
8487
8488
8489        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8490            return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8491        }
8492
8493        return scannedPkg;
8494    }
8495
8496    /**
8497     * Returns if full apk verification can be skipped for the whole package, including the splits.
8498     */
8499    private boolean canSkipFullPackageVerification(PackageParser.Package pkg) {
8500        if (!canSkipFullApkVerification(pkg.baseCodePath)) {
8501            return false;
8502        }
8503        // TODO: Allow base and splits to be verified individually.
8504        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8505            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8506                if (!canSkipFullApkVerification(pkg.splitCodePaths[i])) {
8507                    return false;
8508                }
8509            }
8510        }
8511        return true;
8512    }
8513
8514    /**
8515     * Returns if full apk verification can be skipped, depending on current FSVerity setup and
8516     * whether the apk contains signed root hash.  Note that the signer's certificate still needs to
8517     * match one in a trusted source, and should be done separately.
8518     */
8519    private boolean canSkipFullApkVerification(String apkPath) {
8520        byte[] rootHashObserved = null;
8521        try {
8522            rootHashObserved = VerityUtils.generateFsverityRootHash(apkPath);
8523            if (rootHashObserved == null) {
8524                return false;  // APK does not contain Merkle tree root hash.
8525            }
8526            synchronized (mInstallLock) {
8527                // Returns whether the observed root hash matches what kernel has.
8528                mInstaller.assertFsverityRootHashMatches(apkPath, rootHashObserved);
8529                return true;
8530            }
8531        } catch (InstallerException | IOException | DigestException |
8532                NoSuchAlgorithmException e) {
8533            Slog.w(TAG, "Error in fsverity check. Fallback to full apk verification.", e);
8534        }
8535        return false;
8536    }
8537
8538    // Temporary to catch potential issues with refactoring
8539    private static boolean REFACTOR_DEBUG = true;
8540    /**
8541     * Adds a new package to the internal data structures during platform initialization.
8542     * <p>After adding, the package is known to the system and available for querying.
8543     * <p>For packages located on the device ROM [eg. packages located in /system, /vendor,
8544     * etc...], additional checks are performed. Basic verification [such as ensuring
8545     * matching signatures, checking version codes, etc...] occurs if the package is
8546     * identical to a previously known package. If the package fails a signature check,
8547     * the version installed on /data will be removed. If the version of the new package
8548     * is less than or equal than the version on /data, it will be ignored.
8549     * <p>Regardless of the package location, the results are applied to the internal
8550     * structures and the package is made available to the rest of the system.
8551     * <p>NOTE: The return value should be removed. It's the passed in package object.
8552     */
8553    private PackageParser.Package addForInitLI(PackageParser.Package pkg,
8554            @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8555            @Nullable UserHandle user)
8556                    throws PackageManagerException {
8557        final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0;
8558        final String renamedPkgName;
8559        final PackageSetting disabledPkgSetting;
8560        final boolean isSystemPkgUpdated;
8561        final boolean pkgAlreadyExists;
8562        PackageSetting pkgSetting;
8563
8564        // NOTE: installPackageLI() has the same code to setup the package's
8565        // application info. This probably should be done lower in the call
8566        // stack [such as scanPackageOnly()]. However, we verify the application
8567        // info prior to that [in scanPackageNew()] and thus have to setup
8568        // the application info early.
8569        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8570        pkg.setApplicationInfoCodePath(pkg.codePath);
8571        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8572        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8573        pkg.setApplicationInfoResourcePath(pkg.codePath);
8574        pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
8575        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8576
8577        synchronized (mPackages) {
8578            renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8579            final String realPkgName = getRealPackageName(pkg, renamedPkgName);
8580if (REFACTOR_DEBUG) {
8581Slog.e("TODD",
8582        "Add pkg: " + pkg.packageName + (realPkgName==null?"":", realName: " + realPkgName));
8583}
8584            if (realPkgName != null) {
8585                ensurePackageRenamed(pkg, renamedPkgName);
8586            }
8587            final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
8588            final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName);
8589            pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting;
8590            pkgAlreadyExists = pkgSetting != null;
8591            final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName;
8592            disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName);
8593            isSystemPkgUpdated = disabledPkgSetting != null;
8594
8595            if (DEBUG_INSTALL && isSystemPkgUpdated) {
8596                Slog.d(TAG, "updatedPkg = " + disabledPkgSetting);
8597            }
8598if (REFACTOR_DEBUG) {
8599Slog.e("TODD",
8600        "SSP? " + scanSystemPartition
8601        + ", exists? " + pkgAlreadyExists + (pkgAlreadyExists?" "+pkgSetting.toString():"")
8602        + ", upgraded? " + isSystemPkgUpdated + (isSystemPkgUpdated?" "+disabledPkgSetting.toString():""));
8603}
8604
8605            final SharedUserSetting sharedUserSetting = (pkg.mSharedUserId != null)
8606                    ? mSettings.getSharedUserLPw(pkg.mSharedUserId,
8607                            0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true)
8608                    : null;
8609            if (DEBUG_PACKAGE_SCANNING
8610                    && (parseFlags & PackageParser.PARSE_CHATTY) != 0
8611                    && sharedUserSetting != null) {
8612                Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
8613                        + " (uid=" + sharedUserSetting.userId + "):"
8614                        + " packages=" + sharedUserSetting.packages);
8615if (REFACTOR_DEBUG) {
8616Slog.e("TODD",
8617        "Shared UserID " + pkg.mSharedUserId
8618        + " (uid=" + sharedUserSetting.userId + "):"
8619        + " packages=" + sharedUserSetting.packages);
8620}
8621            }
8622
8623            if (scanSystemPartition) {
8624                // Potentially prune child packages. If the application on the /system
8625                // partition has been updated via OTA, but, is still disabled by a
8626                // version on /data, cycle through all of its children packages and
8627                // remove children that are no longer defined.
8628                if (isSystemPkgUpdated) {
8629if (REFACTOR_DEBUG) {
8630Slog.e("TODD",
8631        "Disable child packages");
8632}
8633                    final int scannedChildCount = (pkg.childPackages != null)
8634                            ? pkg.childPackages.size() : 0;
8635                    final int disabledChildCount = disabledPkgSetting.childPackageNames != null
8636                            ? disabledPkgSetting.childPackageNames.size() : 0;
8637                    for (int i = 0; i < disabledChildCount; i++) {
8638                        String disabledChildPackageName =
8639                                disabledPkgSetting.childPackageNames.get(i);
8640                        boolean disabledPackageAvailable = false;
8641                        for (int j = 0; j < scannedChildCount; j++) {
8642                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8643                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8644if (REFACTOR_DEBUG) {
8645Slog.e("TODD",
8646        "Ignore " + disabledChildPackageName);
8647}
8648                                disabledPackageAvailable = true;
8649                                break;
8650                            }
8651                        }
8652                        if (!disabledPackageAvailable) {
8653if (REFACTOR_DEBUG) {
8654Slog.e("TODD",
8655        "Disable " + disabledChildPackageName);
8656}
8657                            mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8658                        }
8659                    }
8660                    // we're updating the disabled package, so, scan it as the package setting
8661                    final ScanRequest request = new ScanRequest(pkg, sharedUserSetting,
8662                            disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */,
8663                            null /* originalPkgSetting */, null, parseFlags, scanFlags,
8664                            (pkg == mPlatformPackage), user);
8665if (REFACTOR_DEBUG) {
8666Slog.e("TODD",
8667        "Scan disabled system package");
8668Slog.e("TODD",
8669        "Pre: " + request.pkgSetting.dumpState_temp());
8670}
8671final ScanResult result =
8672                    scanPackageOnlyLI(request, mFactoryTest, -1L);
8673if (REFACTOR_DEBUG) {
8674Slog.e("TODD",
8675        "Post: " + (result.success?result.pkgSetting.dumpState_temp():"FAILED scan"));
8676}
8677                }
8678            }
8679        }
8680
8681        final boolean newPkgChangedPaths =
8682                pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath);
8683if (REFACTOR_DEBUG) {
8684Slog.e("TODD",
8685        "paths changed? " + newPkgChangedPaths
8686        + "; old: " + pkg.codePath
8687        + ", new: " + (pkgSetting==null?"<<NULL>>":pkgSetting.codePathString));
8688}
8689        final boolean newPkgVersionGreater =
8690                pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode;
8691if (REFACTOR_DEBUG) {
8692Slog.e("TODD",
8693        "version greater? " + newPkgVersionGreater
8694        + "; old: " + pkg.getLongVersionCode()
8695        + ", new: " + (pkgSetting==null?"<<NULL>>":pkgSetting.versionCode));
8696}
8697        final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated
8698                && newPkgChangedPaths && newPkgVersionGreater;
8699if (REFACTOR_DEBUG) {
8700    Slog.e("TODD",
8701            "system better? " + isSystemPkgBetter);
8702}
8703        if (isSystemPkgBetter) {
8704            // The version of the application on /system is greater than the version on
8705            // /data. Switch back to the application on /system.
8706            // It's safe to assume the application on /system will correctly scan. If not,
8707            // there won't be a working copy of the application.
8708            synchronized (mPackages) {
8709                // just remove the loaded entries from package lists
8710                mPackages.remove(pkgSetting.name);
8711            }
8712
8713            logCriticalInfo(Log.WARN,
8714                    "System package updated;"
8715                    + " name: " + pkgSetting.name
8716                    + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8717                    + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8718if (REFACTOR_DEBUG) {
8719Slog.e("TODD",
8720        "System package changed;"
8721        + " name: " + pkgSetting.name
8722        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8723        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8724}
8725
8726            final InstallArgs args = createInstallArgsForExisting(
8727                    packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8728                    pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8729            args.cleanUpResourcesLI();
8730            synchronized (mPackages) {
8731                mSettings.enableSystemPackageLPw(pkgSetting.name);
8732            }
8733        }
8734
8735        if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) {
8736if (REFACTOR_DEBUG) {
8737Slog.e("TODD",
8738        "THROW exception; system pkg version not good enough");
8739}
8740            // The version of the application on the /system partition is less than or
8741            // equal to the version on the /data partition. Throw an exception and use
8742            // the application already installed on the /data partition.
8743            throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at "
8744                    + pkg.codePath + " ignored: updated version " + disabledPkgSetting.versionCode
8745                    + " better than this " + pkg.getLongVersionCode());
8746        }
8747
8748        // Verify certificates against what was last scanned. If it is an updated priv app, we will
8749        // force re-collecting certificate. Full apk verification will happen unless apk verity is
8750        // set up for the file. In that case, only small part of the apk is verified upfront.
8751        final boolean forceCollect = PackageManagerServiceUtils.isApkVerificationForced(
8752                disabledPkgSetting);
8753        collectCertificatesLI(pkgSetting, pkg, forceCollect);
8754
8755        boolean shouldHideSystemApp = false;
8756        // A new application appeared on /system, but, we already have a copy of
8757        // the application installed on /data.
8758        if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists
8759                && !pkgSetting.isSystem()) {
8760            // if the signatures don't match, wipe the installed application and its data
8761            if (compareSignatures(pkgSetting.signatures.mSigningDetails.signatures,
8762                    pkg.mSigningDetails.signatures)
8763                            != PackageManager.SIGNATURE_MATCH) {
8764                logCriticalInfo(Log.WARN,
8765                        "System package signature mismatch;"
8766                        + " name: " + pkgSetting.name);
8767if (REFACTOR_DEBUG) {
8768Slog.e("TODD",
8769        "System package signature mismatch;"
8770        + " name: " + pkgSetting.name);
8771}
8772                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8773                        "scanPackageInternalLI")) {
8774                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8775                }
8776                pkgSetting = null;
8777            } else if (newPkgVersionGreater) {
8778                // The application on /system is newer than the application on /data.
8779                // Simply remove the application on /data [keeping application data]
8780                // and replace it with the version on /system.
8781                logCriticalInfo(Log.WARN,
8782                        "System package enabled;"
8783                        + " name: " + pkgSetting.name
8784                        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8785                        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8786if (REFACTOR_DEBUG) {
8787Slog.e("TODD",
8788        "System package enabled;"
8789        + " name: " + pkgSetting.name
8790        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8791        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8792}
8793                InstallArgs args = createInstallArgsForExisting(
8794                        packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8795                        pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8796                synchronized (mInstallLock) {
8797                    args.cleanUpResourcesLI();
8798                }
8799            } else {
8800                // The application on /system is older than the application on /data. Hide
8801                // the application on /system and the version on /data will be scanned later
8802                // and re-added like an update.
8803                shouldHideSystemApp = true;
8804                logCriticalInfo(Log.INFO,
8805                        "System package disabled;"
8806                        + " name: " + pkgSetting.name
8807                        + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode
8808                        + "; new: " + pkg.codePath + " @ " + pkg.codePath);
8809if (REFACTOR_DEBUG) {
8810Slog.e("TODD",
8811        "System package disabled;"
8812        + " name: " + pkgSetting.name
8813        + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode
8814        + "; new: " + pkg.codePath + " @ " + pkg.codePath);
8815}
8816            }
8817        }
8818
8819if (REFACTOR_DEBUG) {
8820Slog.e("TODD",
8821        "Scan package");
8822Slog.e("TODD",
8823        "Pre: " + (pkgSetting==null?"<<NONE>>":pkgSetting.dumpState_temp()));
8824}
8825        final PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags
8826                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8827if (REFACTOR_DEBUG) {
8828pkgSetting = mSettings.getPackageLPr(pkg.packageName);
8829Slog.e("TODD",
8830        "Post: " + (pkgSetting==null?"<<NONE>>":pkgSetting.dumpState_temp()));
8831}
8832
8833        if (shouldHideSystemApp) {
8834if (REFACTOR_DEBUG) {
8835Slog.e("TODD",
8836        "Disable package: " + pkg.packageName);
8837}
8838            synchronized (mPackages) {
8839                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8840            }
8841        }
8842        return scannedPkg;
8843    }
8844
8845    private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8846        // Derive the new package synthetic package name
8847        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8848                + pkg.staticSharedLibVersion);
8849    }
8850
8851    private static String fixProcessName(String defProcessName,
8852            String processName) {
8853        if (processName == null) {
8854            return defProcessName;
8855        }
8856        return processName;
8857    }
8858
8859    /**
8860     * Enforces that only the system UID or root's UID can call a method exposed
8861     * via Binder.
8862     *
8863     * @param message used as message if SecurityException is thrown
8864     * @throws SecurityException if the caller is not system or root
8865     */
8866    private static final void enforceSystemOrRoot(String message) {
8867        final int uid = Binder.getCallingUid();
8868        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8869            throw new SecurityException(message);
8870        }
8871    }
8872
8873    @Override
8874    public void performFstrimIfNeeded() {
8875        enforceSystemOrRoot("Only the system can request fstrim");
8876
8877        // Before everything else, see whether we need to fstrim.
8878        try {
8879            IStorageManager sm = PackageHelper.getStorageManager();
8880            if (sm != null) {
8881                boolean doTrim = false;
8882                final long interval = android.provider.Settings.Global.getLong(
8883                        mContext.getContentResolver(),
8884                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8885                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8886                if (interval > 0) {
8887                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8888                    if (timeSinceLast > interval) {
8889                        doTrim = true;
8890                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8891                                + "; running immediately");
8892                    }
8893                }
8894                if (doTrim) {
8895                    final boolean dexOptDialogShown;
8896                    synchronized (mPackages) {
8897                        dexOptDialogShown = mDexOptDialogShown;
8898                    }
8899                    if (!isFirstBoot() && dexOptDialogShown) {
8900                        try {
8901                            ActivityManager.getService().showBootMessage(
8902                                    mContext.getResources().getString(
8903                                            R.string.android_upgrading_fstrim), true);
8904                        } catch (RemoteException e) {
8905                        }
8906                    }
8907                    sm.runMaintenance();
8908                }
8909            } else {
8910                Slog.e(TAG, "storageManager service unavailable!");
8911            }
8912        } catch (RemoteException e) {
8913            // Can't happen; StorageManagerService is local
8914        }
8915    }
8916
8917    @Override
8918    public void updatePackagesIfNeeded() {
8919        enforceSystemOrRoot("Only the system can request package update");
8920
8921        // We need to re-extract after an OTA.
8922        boolean causeUpgrade = isUpgrade();
8923
8924        // First boot or factory reset.
8925        // Note: we also handle devices that are upgrading to N right now as if it is their
8926        //       first boot, as they do not have profile data.
8927        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8928
8929        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8930        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8931
8932        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8933            return;
8934        }
8935
8936        List<PackageParser.Package> pkgs;
8937        synchronized (mPackages) {
8938            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8939        }
8940
8941        final long startTime = System.nanoTime();
8942        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8943                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
8944                    false /* bootComplete */);
8945
8946        final int elapsedTimeSeconds =
8947                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8948
8949        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8950        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8951        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8952        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8953        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8954    }
8955
8956    /*
8957     * Return the prebuilt profile path given a package base code path.
8958     */
8959    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
8960        return pkg.baseCodePath + ".prof";
8961    }
8962
8963    /**
8964     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8965     * containing statistics about the invocation. The array consists of three elements,
8966     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8967     * and {@code numberOfPackagesFailed}.
8968     */
8969    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8970            final String compilerFilter, boolean bootComplete) {
8971
8972        int numberOfPackagesVisited = 0;
8973        int numberOfPackagesOptimized = 0;
8974        int numberOfPackagesSkipped = 0;
8975        int numberOfPackagesFailed = 0;
8976        final int numberOfPackagesToDexopt = pkgs.size();
8977
8978        for (PackageParser.Package pkg : pkgs) {
8979            numberOfPackagesVisited++;
8980
8981            boolean useProfileForDexopt = false;
8982
8983            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
8984                // Copy over initial preopt profiles since we won't get any JIT samples for methods
8985                // that are already compiled.
8986                File profileFile = new File(getPrebuildProfilePath(pkg));
8987                // Copy profile if it exists.
8988                if (profileFile.exists()) {
8989                    try {
8990                        // We could also do this lazily before calling dexopt in
8991                        // PackageDexOptimizer to prevent this happening on first boot. The issue
8992                        // is that we don't have a good way to say "do this only once".
8993                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8994                                pkg.applicationInfo.uid, pkg.packageName,
8995                                ArtManager.getProfileName(null))) {
8996                            Log.e(TAG, "Installer failed to copy system profile!");
8997                        } else {
8998                            // Disabled as this causes speed-profile compilation during first boot
8999                            // even if things are already compiled.
9000                            // useProfileForDexopt = true;
9001                        }
9002                    } catch (Exception e) {
9003                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9004                                e);
9005                    }
9006                } else {
9007                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9008                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
9009                    // minimize the number off apps being speed-profile compiled during first boot.
9010                    // The other paths will not change the filter.
9011                    if (disabledPs != null && disabledPs.pkg.isStub) {
9012                        // The package is the stub one, remove the stub suffix to get the normal
9013                        // package and APK names.
9014                        String systemProfilePath =
9015                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
9016                        profileFile = new File(systemProfilePath);
9017                        // If we have a profile for a compressed APK, copy it to the reference
9018                        // location.
9019                        // Note that copying the profile here will cause it to override the
9020                        // reference profile every OTA even though the existing reference profile
9021                        // may have more data. We can't copy during decompression since the
9022                        // directories are not set up at that point.
9023                        if (profileFile.exists()) {
9024                            try {
9025                                // We could also do this lazily before calling dexopt in
9026                                // PackageDexOptimizer to prevent this happening on first boot. The
9027                                // issue is that we don't have a good way to say "do this only
9028                                // once".
9029                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9030                                        pkg.applicationInfo.uid, pkg.packageName,
9031                                        ArtManager.getProfileName(null))) {
9032                                    Log.e(TAG, "Failed to copy system profile for stub package!");
9033                                } else {
9034                                    useProfileForDexopt = true;
9035                                }
9036                            } catch (Exception e) {
9037                                Log.e(TAG, "Failed to copy profile " +
9038                                        profileFile.getAbsolutePath() + " ", e);
9039                            }
9040                        }
9041                    }
9042                }
9043            }
9044
9045            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9046                if (DEBUG_DEXOPT) {
9047                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9048                }
9049                numberOfPackagesSkipped++;
9050                continue;
9051            }
9052
9053            if (DEBUG_DEXOPT) {
9054                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9055                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9056            }
9057
9058            if (showDialog) {
9059                try {
9060                    ActivityManager.getService().showBootMessage(
9061                            mContext.getResources().getString(R.string.android_upgrading_apk,
9062                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9063                } catch (RemoteException e) {
9064                }
9065                synchronized (mPackages) {
9066                    mDexOptDialogShown = true;
9067                }
9068            }
9069
9070            String pkgCompilerFilter = compilerFilter;
9071            if (useProfileForDexopt) {
9072                // Use background dexopt mode to try and use the profile. Note that this does not
9073                // guarantee usage of the profile.
9074                pkgCompilerFilter =
9075                        PackageManagerServiceCompilerMapping.getCompilerFilterForReason(
9076                                PackageManagerService.REASON_BACKGROUND_DEXOPT);
9077            }
9078
9079            // checkProfiles is false to avoid merging profiles during boot which
9080            // might interfere with background compilation (b/28612421).
9081            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9082            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9083            // trade-off worth doing to save boot time work.
9084            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9085            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9086                    pkg.packageName,
9087                    pkgCompilerFilter,
9088                    dexoptFlags));
9089
9090            switch (primaryDexOptStaus) {
9091                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9092                    numberOfPackagesOptimized++;
9093                    break;
9094                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9095                    numberOfPackagesSkipped++;
9096                    break;
9097                case PackageDexOptimizer.DEX_OPT_FAILED:
9098                    numberOfPackagesFailed++;
9099                    break;
9100                default:
9101                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9102                    break;
9103            }
9104        }
9105
9106        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9107                numberOfPackagesFailed };
9108    }
9109
9110    @Override
9111    public void notifyPackageUse(String packageName, int reason) {
9112        synchronized (mPackages) {
9113            final int callingUid = Binder.getCallingUid();
9114            final int callingUserId = UserHandle.getUserId(callingUid);
9115            if (getInstantAppPackageName(callingUid) != null) {
9116                if (!isCallerSameApp(packageName, callingUid)) {
9117                    return;
9118                }
9119            } else {
9120                if (isInstantApp(packageName, callingUserId)) {
9121                    return;
9122                }
9123            }
9124            notifyPackageUseLocked(packageName, reason);
9125        }
9126    }
9127
9128    private void notifyPackageUseLocked(String packageName, int reason) {
9129        final PackageParser.Package p = mPackages.get(packageName);
9130        if (p == null) {
9131            return;
9132        }
9133        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9134    }
9135
9136    @Override
9137    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9138            List<String> classPaths, String loaderIsa) {
9139        int userId = UserHandle.getCallingUserId();
9140        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9141        if (ai == null) {
9142            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9143                + loadingPackageName + ", user=" + userId);
9144            return;
9145        }
9146        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9147    }
9148
9149    @Override
9150    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9151            IDexModuleRegisterCallback callback) {
9152        int userId = UserHandle.getCallingUserId();
9153        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9154        DexManager.RegisterDexModuleResult result;
9155        if (ai == null) {
9156            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9157                     " calling user. package=" + packageName + ", user=" + userId);
9158            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9159        } else {
9160            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9161        }
9162
9163        if (callback != null) {
9164            mHandler.post(() -> {
9165                try {
9166                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9167                } catch (RemoteException e) {
9168                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9169                }
9170            });
9171        }
9172    }
9173
9174    /**
9175     * Ask the package manager to perform a dex-opt with the given compiler filter.
9176     *
9177     * Note: exposed only for the shell command to allow moving packages explicitly to a
9178     *       definite state.
9179     */
9180    @Override
9181    public boolean performDexOptMode(String packageName,
9182            boolean checkProfiles, String targetCompilerFilter, boolean force,
9183            boolean bootComplete, String splitName) {
9184        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9185                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9186                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9187        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9188                splitName, flags));
9189    }
9190
9191    /**
9192     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9193     * secondary dex files belonging to the given package.
9194     *
9195     * Note: exposed only for the shell command to allow moving packages explicitly to a
9196     *       definite state.
9197     */
9198    @Override
9199    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9200            boolean force) {
9201        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9202                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9203                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9204                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9205        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9206    }
9207
9208    /*package*/ boolean performDexOpt(DexoptOptions options) {
9209        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9210            return false;
9211        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9212            return false;
9213        }
9214
9215        if (options.isDexoptOnlySecondaryDex()) {
9216            return mDexManager.dexoptSecondaryDex(options);
9217        } else {
9218            int dexoptStatus = performDexOptWithStatus(options);
9219            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9220        }
9221    }
9222
9223    /**
9224     * Perform dexopt on the given package and return one of following result:
9225     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9226     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9227     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9228     */
9229    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9230        return performDexOptTraced(options);
9231    }
9232
9233    private int performDexOptTraced(DexoptOptions options) {
9234        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9235        try {
9236            return performDexOptInternal(options);
9237        } finally {
9238            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9239        }
9240    }
9241
9242    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9243    // if the package can now be considered up to date for the given filter.
9244    private int performDexOptInternal(DexoptOptions options) {
9245        PackageParser.Package p;
9246        synchronized (mPackages) {
9247            p = mPackages.get(options.getPackageName());
9248            if (p == null) {
9249                // Package could not be found. Report failure.
9250                return PackageDexOptimizer.DEX_OPT_FAILED;
9251            }
9252            mPackageUsage.maybeWriteAsync(mPackages);
9253            mCompilerStats.maybeWriteAsync();
9254        }
9255        long callingId = Binder.clearCallingIdentity();
9256        try {
9257            synchronized (mInstallLock) {
9258                return performDexOptInternalWithDependenciesLI(p, options);
9259            }
9260        } finally {
9261            Binder.restoreCallingIdentity(callingId);
9262        }
9263    }
9264
9265    public ArraySet<String> getOptimizablePackages() {
9266        ArraySet<String> pkgs = new ArraySet<String>();
9267        synchronized (mPackages) {
9268            for (PackageParser.Package p : mPackages.values()) {
9269                if (PackageDexOptimizer.canOptimizePackage(p)) {
9270                    pkgs.add(p.packageName);
9271                }
9272            }
9273        }
9274        return pkgs;
9275    }
9276
9277    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9278            DexoptOptions options) {
9279        // Select the dex optimizer based on the force parameter.
9280        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9281        //       allocate an object here.
9282        PackageDexOptimizer pdo = options.isForce()
9283                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9284                : mPackageDexOptimizer;
9285
9286        // Dexopt all dependencies first. Note: we ignore the return value and march on
9287        // on errors.
9288        // Note that we are going to call performDexOpt on those libraries as many times as
9289        // they are referenced in packages. When we do a batch of performDexOpt (for example
9290        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9291        // and the first package that uses the library will dexopt it. The
9292        // others will see that the compiled code for the library is up to date.
9293        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9294        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9295        if (!deps.isEmpty()) {
9296            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9297                    options.getCompilerFilter(), options.getSplitName(),
9298                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9299            for (PackageParser.Package depPackage : deps) {
9300                // TODO: Analyze and investigate if we (should) profile libraries.
9301                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9302                        getOrCreateCompilerPackageStats(depPackage),
9303                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9304            }
9305        }
9306        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9307                getOrCreateCompilerPackageStats(p),
9308                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9309    }
9310
9311    /**
9312     * Reconcile the information we have about the secondary dex files belonging to
9313     * {@code packagName} and the actual dex files. For all dex files that were
9314     * deleted, update the internal records and delete the generated oat files.
9315     */
9316    @Override
9317    public void reconcileSecondaryDexFiles(String packageName) {
9318        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9319            return;
9320        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9321            return;
9322        }
9323        mDexManager.reconcileSecondaryDexFiles(packageName);
9324    }
9325
9326    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9327    // a reference there.
9328    /*package*/ DexManager getDexManager() {
9329        return mDexManager;
9330    }
9331
9332    /**
9333     * Execute the background dexopt job immediately.
9334     */
9335    @Override
9336    public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) {
9337        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9338            return false;
9339        }
9340        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames);
9341    }
9342
9343    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9344        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9345                || p.usesStaticLibraries != null) {
9346            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9347            Set<String> collectedNames = new HashSet<>();
9348            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9349
9350            retValue.remove(p);
9351
9352            return retValue;
9353        } else {
9354            return Collections.emptyList();
9355        }
9356    }
9357
9358    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9359            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9360        if (!collectedNames.contains(p.packageName)) {
9361            collectedNames.add(p.packageName);
9362            collected.add(p);
9363
9364            if (p.usesLibraries != null) {
9365                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9366                        null, collected, collectedNames);
9367            }
9368            if (p.usesOptionalLibraries != null) {
9369                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9370                        null, collected, collectedNames);
9371            }
9372            if (p.usesStaticLibraries != null) {
9373                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9374                        p.usesStaticLibrariesVersions, collected, collectedNames);
9375            }
9376        }
9377    }
9378
9379    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions,
9380            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9381        final int libNameCount = libs.size();
9382        for (int i = 0; i < libNameCount; i++) {
9383            String libName = libs.get(i);
9384            long version = (versions != null && versions.length == libNameCount)
9385                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9386            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9387            if (libPkg != null) {
9388                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9389            }
9390        }
9391    }
9392
9393    private PackageParser.Package findSharedNonSystemLibrary(String name, long version) {
9394        synchronized (mPackages) {
9395            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9396            if (libEntry != null) {
9397                return mPackages.get(libEntry.apk);
9398            }
9399            return null;
9400        }
9401    }
9402
9403    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) {
9404        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9405        if (versionedLib == null) {
9406            return null;
9407        }
9408        return versionedLib.get(version);
9409    }
9410
9411    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9412        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9413                pkg.staticSharedLibName);
9414        if (versionedLib == null) {
9415            return null;
9416        }
9417        long previousLibVersion = -1;
9418        final int versionCount = versionedLib.size();
9419        for (int i = 0; i < versionCount; i++) {
9420            final long libVersion = versionedLib.keyAt(i);
9421            if (libVersion < pkg.staticSharedLibVersion) {
9422                previousLibVersion = Math.max(previousLibVersion, libVersion);
9423            }
9424        }
9425        if (previousLibVersion >= 0) {
9426            return versionedLib.get(previousLibVersion);
9427        }
9428        return null;
9429    }
9430
9431    public void shutdown() {
9432        mPackageUsage.writeNow(mPackages);
9433        mCompilerStats.writeNow();
9434        mDexManager.writePackageDexUsageNow();
9435    }
9436
9437    @Override
9438    public void dumpProfiles(String packageName) {
9439        PackageParser.Package pkg;
9440        synchronized (mPackages) {
9441            pkg = mPackages.get(packageName);
9442            if (pkg == null) {
9443                throw new IllegalArgumentException("Unknown package: " + packageName);
9444            }
9445        }
9446        /* Only the shell, root, or the app user should be able to dump profiles. */
9447        int callingUid = Binder.getCallingUid();
9448        if (callingUid != Process.SHELL_UID &&
9449            callingUid != Process.ROOT_UID &&
9450            callingUid != pkg.applicationInfo.uid) {
9451            throw new SecurityException("dumpProfiles");
9452        }
9453
9454        synchronized (mInstallLock) {
9455            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9456            mArtManagerService.dumpProfiles(pkg);
9457            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9458        }
9459    }
9460
9461    @Override
9462    public void forceDexOpt(String packageName) {
9463        enforceSystemOrRoot("forceDexOpt");
9464
9465        PackageParser.Package pkg;
9466        synchronized (mPackages) {
9467            pkg = mPackages.get(packageName);
9468            if (pkg == null) {
9469                throw new IllegalArgumentException("Unknown package: " + packageName);
9470            }
9471        }
9472
9473        synchronized (mInstallLock) {
9474            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9475
9476            // Whoever is calling forceDexOpt wants a compiled package.
9477            // Don't use profiles since that may cause compilation to be skipped.
9478            final int res = performDexOptInternalWithDependenciesLI(
9479                    pkg,
9480                    new DexoptOptions(packageName,
9481                            getDefaultCompilerFilter(),
9482                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9483
9484            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9485            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9486                throw new IllegalStateException("Failed to dexopt: " + res);
9487            }
9488        }
9489    }
9490
9491    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9492        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9493            Slog.w(TAG, "Unable to update from " + oldPkg.name
9494                    + " to " + newPkg.packageName
9495                    + ": old package not in system partition");
9496            return false;
9497        } else if (mPackages.get(oldPkg.name) != null) {
9498            Slog.w(TAG, "Unable to update from " + oldPkg.name
9499                    + " to " + newPkg.packageName
9500                    + ": old package still exists");
9501            return false;
9502        }
9503        return true;
9504    }
9505
9506    void removeCodePathLI(File codePath) {
9507        if (codePath.isDirectory()) {
9508            try {
9509                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9510            } catch (InstallerException e) {
9511                Slog.w(TAG, "Failed to remove code path", e);
9512            }
9513        } else {
9514            codePath.delete();
9515        }
9516    }
9517
9518    private int[] resolveUserIds(int userId) {
9519        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9520    }
9521
9522    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9523        if (pkg == null) {
9524            Slog.wtf(TAG, "Package was null!", new Throwable());
9525            return;
9526        }
9527        clearAppDataLeafLIF(pkg, userId, flags);
9528        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9529        for (int i = 0; i < childCount; i++) {
9530            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9531        }
9532
9533        clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
9534    }
9535
9536    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9537        final PackageSetting ps;
9538        synchronized (mPackages) {
9539            ps = mSettings.mPackages.get(pkg.packageName);
9540        }
9541        for (int realUserId : resolveUserIds(userId)) {
9542            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9543            try {
9544                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9545                        ceDataInode);
9546            } catch (InstallerException e) {
9547                Slog.w(TAG, String.valueOf(e));
9548            }
9549        }
9550    }
9551
9552    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9553        if (pkg == null) {
9554            Slog.wtf(TAG, "Package was null!", new Throwable());
9555            return;
9556        }
9557        destroyAppDataLeafLIF(pkg, userId, flags);
9558        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9559        for (int i = 0; i < childCount; i++) {
9560            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9561        }
9562    }
9563
9564    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9565        final PackageSetting ps;
9566        synchronized (mPackages) {
9567            ps = mSettings.mPackages.get(pkg.packageName);
9568        }
9569        for (int realUserId : resolveUserIds(userId)) {
9570            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9571            try {
9572                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9573                        ceDataInode);
9574            } catch (InstallerException e) {
9575                Slog.w(TAG, String.valueOf(e));
9576            }
9577            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9578        }
9579    }
9580
9581    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9582        if (pkg == null) {
9583            Slog.wtf(TAG, "Package was null!", new Throwable());
9584            return;
9585        }
9586        destroyAppProfilesLeafLIF(pkg);
9587        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9588        for (int i = 0; i < childCount; i++) {
9589            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9590        }
9591    }
9592
9593    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9594        try {
9595            mInstaller.destroyAppProfiles(pkg.packageName);
9596        } catch (InstallerException e) {
9597            Slog.w(TAG, String.valueOf(e));
9598        }
9599    }
9600
9601    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9602        if (pkg == null) {
9603            Slog.wtf(TAG, "Package was null!", new Throwable());
9604            return;
9605        }
9606        mArtManagerService.clearAppProfiles(pkg);
9607        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9608        for (int i = 0; i < childCount; i++) {
9609            mArtManagerService.clearAppProfiles(pkg.childPackages.get(i));
9610        }
9611    }
9612
9613    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9614            long lastUpdateTime) {
9615        // Set parent install/update time
9616        PackageSetting ps = (PackageSetting) pkg.mExtras;
9617        if (ps != null) {
9618            ps.firstInstallTime = firstInstallTime;
9619            ps.lastUpdateTime = lastUpdateTime;
9620        }
9621        // Set children install/update time
9622        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9623        for (int i = 0; i < childCount; i++) {
9624            PackageParser.Package childPkg = pkg.childPackages.get(i);
9625            ps = (PackageSetting) childPkg.mExtras;
9626            if (ps != null) {
9627                ps.firstInstallTime = firstInstallTime;
9628                ps.lastUpdateTime = lastUpdateTime;
9629            }
9630        }
9631    }
9632
9633    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9634            SharedLibraryEntry file,
9635            PackageParser.Package changingLib) {
9636        if (file.path != null) {
9637            usesLibraryFiles.add(file.path);
9638            return;
9639        }
9640        PackageParser.Package p = mPackages.get(file.apk);
9641        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9642            // If we are doing this while in the middle of updating a library apk,
9643            // then we need to make sure to use that new apk for determining the
9644            // dependencies here.  (We haven't yet finished committing the new apk
9645            // to the package manager state.)
9646            if (p == null || p.packageName.equals(changingLib.packageName)) {
9647                p = changingLib;
9648            }
9649        }
9650        if (p != null) {
9651            usesLibraryFiles.addAll(p.getAllCodePaths());
9652            if (p.usesLibraryFiles != null) {
9653                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9654            }
9655        }
9656    }
9657
9658    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9659            PackageParser.Package changingLib) throws PackageManagerException {
9660        if (pkg == null) {
9661            return;
9662        }
9663        // The collection used here must maintain the order of addition (so
9664        // that libraries are searched in the correct order) and must have no
9665        // duplicates.
9666        Set<String> usesLibraryFiles = null;
9667        if (pkg.usesLibraries != null) {
9668            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9669                    null, null, pkg.packageName, changingLib, true,
9670                    pkg.applicationInfo.targetSdkVersion, null);
9671        }
9672        if (pkg.usesStaticLibraries != null) {
9673            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9674                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9675                    pkg.packageName, changingLib, true,
9676                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9677        }
9678        if (pkg.usesOptionalLibraries != null) {
9679            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9680                    null, null, pkg.packageName, changingLib, false,
9681                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9682        }
9683        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9684            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9685        } else {
9686            pkg.usesLibraryFiles = null;
9687        }
9688    }
9689
9690    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9691            @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests,
9692            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9693            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
9694            throws PackageManagerException {
9695        final int libCount = requestedLibraries.size();
9696        for (int i = 0; i < libCount; i++) {
9697            final String libName = requestedLibraries.get(i);
9698            final long libVersion = requiredVersions != null ? requiredVersions[i]
9699                    : SharedLibraryInfo.VERSION_UNDEFINED;
9700            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9701            if (libEntry == null) {
9702                if (required) {
9703                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9704                            "Package " + packageName + " requires unavailable shared library "
9705                                    + libName + "; failing!");
9706                } else if (DEBUG_SHARED_LIBRARIES) {
9707                    Slog.i(TAG, "Package " + packageName
9708                            + " desires unavailable shared library "
9709                            + libName + "; ignoring!");
9710                }
9711            } else {
9712                if (requiredVersions != null && requiredCertDigests != null) {
9713                    if (libEntry.info.getLongVersion() != requiredVersions[i]) {
9714                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9715                            "Package " + packageName + " requires unavailable static shared"
9716                                    + " library " + libName + " version "
9717                                    + libEntry.info.getLongVersion() + "; failing!");
9718                    }
9719
9720                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9721                    if (libPkg == null) {
9722                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9723                                "Package " + packageName + " requires unavailable static shared"
9724                                        + " library; failing!");
9725                    }
9726
9727                    final String[] expectedCertDigests = requiredCertDigests[i];
9728                    // For apps targeting O MR1 we require explicit enumeration of all certs.
9729                    final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
9730                            ? PackageUtils.computeSignaturesSha256Digests(
9731                            libPkg.mSigningDetails.signatures)
9732                            : PackageUtils.computeSignaturesSha256Digests(
9733                                    new Signature[]{libPkg.mSigningDetails.signatures[0]});
9734
9735                    // Take a shortcut if sizes don't match. Note that if an app doesn't
9736                    // target O we don't parse the "additional-certificate" tags similarly
9737                    // how we only consider all certs only for apps targeting O (see above).
9738                    // Therefore, the size check is safe to make.
9739                    if (expectedCertDigests.length != libCertDigests.length) {
9740                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9741                                "Package " + packageName + " requires differently signed" +
9742                                        " static shared library; failing!");
9743                    }
9744
9745                    // Use a predictable order as signature order may vary
9746                    Arrays.sort(libCertDigests);
9747                    Arrays.sort(expectedCertDigests);
9748
9749                    final int certCount = libCertDigests.length;
9750                    for (int j = 0; j < certCount; j++) {
9751                        if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
9752                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9753                                    "Package " + packageName + " requires differently signed" +
9754                                            " static shared library; failing!");
9755                        }
9756                    }
9757                }
9758
9759                if (outUsedLibraries == null) {
9760                    // Use LinkedHashSet to preserve the order of files added to
9761                    // usesLibraryFiles while eliminating duplicates.
9762                    outUsedLibraries = new LinkedHashSet<>();
9763                }
9764                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9765            }
9766        }
9767        return outUsedLibraries;
9768    }
9769
9770    private static boolean hasString(List<String> list, List<String> which) {
9771        if (list == null) {
9772            return false;
9773        }
9774        for (int i=list.size()-1; i>=0; i--) {
9775            for (int j=which.size()-1; j>=0; j--) {
9776                if (which.get(j).equals(list.get(i))) {
9777                    return true;
9778                }
9779            }
9780        }
9781        return false;
9782    }
9783
9784    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9785            PackageParser.Package changingPkg) {
9786        ArrayList<PackageParser.Package> res = null;
9787        for (PackageParser.Package pkg : mPackages.values()) {
9788            if (changingPkg != null
9789                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9790                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9791                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9792                            changingPkg.staticSharedLibName)) {
9793                return null;
9794            }
9795            if (res == null) {
9796                res = new ArrayList<>();
9797            }
9798            res.add(pkg);
9799            try {
9800                updateSharedLibrariesLPr(pkg, changingPkg);
9801            } catch (PackageManagerException e) {
9802                // If a system app update or an app and a required lib missing we
9803                // delete the package and for updated system apps keep the data as
9804                // it is better for the user to reinstall than to be in an limbo
9805                // state. Also libs disappearing under an app should never happen
9806                // - just in case.
9807                if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) {
9808                    final int flags = pkg.isUpdatedSystemApp()
9809                            ? PackageManager.DELETE_KEEP_DATA : 0;
9810                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9811                            flags , null, true, null);
9812                }
9813                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9814            }
9815        }
9816        return res;
9817    }
9818
9819    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9820            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9821            @Nullable UserHandle user) throws PackageManagerException {
9822        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9823        // If the package has children and this is the first dive in the function
9824        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9825        // whether all packages (parent and children) would be successfully scanned
9826        // before the actual scan since scanning mutates internal state and we want
9827        // to atomically install the package and its children.
9828        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9829            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9830                scanFlags |= SCAN_CHECK_ONLY;
9831            }
9832        } else {
9833            scanFlags &= ~SCAN_CHECK_ONLY;
9834        }
9835
9836        final PackageParser.Package scannedPkg;
9837        try {
9838            // Scan the parent
9839            scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user);
9840            // Scan the children
9841            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9842            for (int i = 0; i < childCount; i++) {
9843                PackageParser.Package childPkg = pkg.childPackages.get(i);
9844                scanPackageNewLI(childPkg, parseFlags,
9845                        scanFlags, currentTime, user);
9846            }
9847        } finally {
9848            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9849        }
9850
9851        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9852            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
9853        }
9854
9855        return scannedPkg;
9856    }
9857
9858    /** The result of a package scan. */
9859    private static class ScanResult {
9860        /** Whether or not the package scan was successful */
9861        public final boolean success;
9862        /**
9863         * The final package settings. This may be the same object passed in
9864         * the {@link ScanRequest}, but, with modified values.
9865         */
9866        @Nullable public final PackageSetting pkgSetting;
9867        /** ABI code paths that have changed in the package scan */
9868        @Nullable public final List<String> changedAbiCodePath;
9869        public ScanResult(
9870                boolean success,
9871                @Nullable PackageSetting pkgSetting,
9872                @Nullable List<String> changedAbiCodePath) {
9873            this.success = success;
9874            this.pkgSetting = pkgSetting;
9875            this.changedAbiCodePath = changedAbiCodePath;
9876        }
9877    }
9878
9879    /** A package to be scanned */
9880    private static class ScanRequest {
9881        /** The parsed package */
9882        @NonNull public final PackageParser.Package pkg;
9883        /** Shared user settings, if the package has a shared user */
9884        @Nullable public final SharedUserSetting sharedUserSetting;
9885        /**
9886         * Package settings of the currently installed version.
9887         * <p><em>IMPORTANT:</em> The contents of this object may be modified
9888         * during scan.
9889         */
9890        @Nullable public final PackageSetting pkgSetting;
9891        /** A copy of the settings for the currently installed version */
9892        @Nullable public final PackageSetting oldPkgSetting;
9893        /** Package settings for the disabled version on the /system partition */
9894        @Nullable public final PackageSetting disabledPkgSetting;
9895        /** Package settings for the installed version under its original package name */
9896        @Nullable public final PackageSetting originalPkgSetting;
9897        /** The real package name of a renamed application */
9898        @Nullable public final String realPkgName;
9899        public final @ParseFlags int parseFlags;
9900        public final @ScanFlags int scanFlags;
9901        /** The user for which the package is being scanned */
9902        @Nullable public final UserHandle user;
9903        /** Whether or not the platform package is being scanned */
9904        public final boolean isPlatformPackage;
9905        public ScanRequest(
9906                @NonNull PackageParser.Package pkg,
9907                @Nullable SharedUserSetting sharedUserSetting,
9908                @Nullable PackageSetting pkgSetting,
9909                @Nullable PackageSetting disabledPkgSetting,
9910                @Nullable PackageSetting originalPkgSetting,
9911                @Nullable String realPkgName,
9912                @ParseFlags int parseFlags,
9913                @ScanFlags int scanFlags,
9914                boolean isPlatformPackage,
9915                @Nullable UserHandle user) {
9916            this.pkg = pkg;
9917            this.pkgSetting = pkgSetting;
9918            this.sharedUserSetting = sharedUserSetting;
9919            this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting);
9920            this.disabledPkgSetting = disabledPkgSetting;
9921            this.originalPkgSetting = originalPkgSetting;
9922            this.realPkgName = realPkgName;
9923            this.parseFlags = parseFlags;
9924            this.scanFlags = scanFlags;
9925            this.isPlatformPackage = isPlatformPackage;
9926            this.user = user;
9927        }
9928    }
9929
9930    /**
9931     * Returns the actual scan flags depending upon the state of the other settings.
9932     * <p>Updated system applications will not have the following flags set
9933     * by default and need to be adjusted after the fact:
9934     * <ul>
9935     * <li>{@link #SCAN_AS_SYSTEM}</li>
9936     * <li>{@link #SCAN_AS_PRIVILEGED}</li>
9937     * <li>{@link #SCAN_AS_OEM}</li>
9938     * <li>{@link #SCAN_AS_VENDOR}</li>
9939     * <li>{@link #SCAN_AS_PRODUCT}</li>
9940     * <li>{@link #SCAN_AS_INSTANT_APP}</li>
9941     * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li>
9942     * </ul>
9943     */
9944    private @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags,
9945            PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user,
9946            PackageParser.Package pkg) {
9947        if (disabledPkgSetting != null) {
9948            // updated system application, must at least have SCAN_AS_SYSTEM
9949            scanFlags |= SCAN_AS_SYSTEM;
9950            if ((disabledPkgSetting.pkgPrivateFlags
9951                    & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9952                scanFlags |= SCAN_AS_PRIVILEGED;
9953            }
9954            if ((disabledPkgSetting.pkgPrivateFlags
9955                    & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
9956                scanFlags |= SCAN_AS_OEM;
9957            }
9958            if ((disabledPkgSetting.pkgPrivateFlags
9959                    & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) {
9960                scanFlags |= SCAN_AS_VENDOR;
9961            }
9962            if ((disabledPkgSetting.pkgPrivateFlags
9963                    & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0) {
9964                scanFlags |= SCAN_AS_PRODUCT;
9965            }
9966        }
9967        if (pkgSetting != null) {
9968            final int userId = ((user == null) ? 0 : user.getIdentifier());
9969            if (pkgSetting.getInstantApp(userId)) {
9970                scanFlags |= SCAN_AS_INSTANT_APP;
9971            }
9972            if (pkgSetting.getVirtulalPreload(userId)) {
9973                scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9974            }
9975        }
9976
9977        // Scan as privileged apps that share a user with a priv-app.
9978        if (((scanFlags & SCAN_AS_PRIVILEGED) == 0) && !pkg.isPrivileged()
9979                && (pkg.mSharedUserId != null)) {
9980            SharedUserSetting sharedUserSetting = null;
9981            try {
9982                sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
9983            } catch (PackageManagerException ignore) {}
9984            if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
9985                // Exempt SharedUsers signed with the platform key.
9986                // TODO(b/72378145) Fix this exemption. Force signature apps
9987                // to whitelist their privileged permissions just like other
9988                // priv-apps.
9989                synchronized (mPackages) {
9990                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
9991                    if ((compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures,
9992                                pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) {
9993                        scanFlags |= SCAN_AS_PRIVILEGED;
9994                    }
9995                }
9996            }
9997        }
9998
9999        return scanFlags;
10000    }
10001
10002    @GuardedBy("mInstallLock")
10003    private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg,
10004            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
10005            @Nullable UserHandle user) throws PackageManagerException {
10006
10007        final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10008        final String realPkgName = getRealPackageName(pkg, renamedPkgName);
10009        if (realPkgName != null) {
10010            ensurePackageRenamed(pkg, renamedPkgName);
10011        }
10012        final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
10013        final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10014        final PackageSetting disabledPkgSetting =
10015                mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10016
10017        if (mTransferedPackages.contains(pkg.packageName)) {
10018            Slog.w(TAG, "Package " + pkg.packageName
10019                    + " was transferred to another, but its .apk remains");
10020        }
10021
10022        scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user, pkg);
10023        synchronized (mPackages) {
10024            applyPolicy(pkg, parseFlags, scanFlags);
10025            assertPackageIsValid(pkg, parseFlags, scanFlags);
10026
10027            SharedUserSetting sharedUserSetting = null;
10028            if (pkg.mSharedUserId != null) {
10029                // SIDE EFFECTS; may potentially allocate a new shared user
10030                sharedUserSetting = mSettings.getSharedUserLPw(
10031                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10032                if (DEBUG_PACKAGE_SCANNING) {
10033                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10034                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
10035                                + " (uid=" + sharedUserSetting.userId + "):"
10036                                + " packages=" + sharedUserSetting.packages);
10037                }
10038            }
10039
10040            boolean scanSucceeded = false;
10041            try {
10042                final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, pkgSetting,
10043                        disabledPkgSetting, originalPkgSetting, realPkgName, parseFlags, scanFlags,
10044                        (pkg == mPlatformPackage), user);
10045                final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime);
10046                if (result.success) {
10047                    commitScanResultsLocked(request, result);
10048                }
10049                scanSucceeded = true;
10050            } finally {
10051                  if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10052                      // DELETE_DATA_ON_FAILURES is only used by frozen paths
10053                      destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10054                              StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10055                      destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10056                  }
10057            }
10058        }
10059        return pkg;
10060    }
10061
10062    /**
10063     * Commits the package scan and modifies system state.
10064     * <p><em>WARNING:</em> The method may throw an excpetion in the middle
10065     * of committing the package, leaving the system in an inconsistent state.
10066     * This needs to be fixed so, once we get to this point, no errors are
10067     * possible and the system is not left in an inconsistent state.
10068     */
10069    @GuardedBy("mPackages")
10070    private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result)
10071            throws PackageManagerException {
10072        final PackageParser.Package pkg = request.pkg;
10073        final @ParseFlags int parseFlags = request.parseFlags;
10074        final @ScanFlags int scanFlags = request.scanFlags;
10075        final PackageSetting oldPkgSetting = request.oldPkgSetting;
10076        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10077        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10078        final UserHandle user = request.user;
10079        final String realPkgName = request.realPkgName;
10080        final PackageSetting pkgSetting = result.pkgSetting;
10081        final List<String> changedAbiCodePath = result.changedAbiCodePath;
10082        final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting);
10083
10084        if (newPkgSettingCreated) {
10085            if (originalPkgSetting != null) {
10086                mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name);
10087            }
10088            // THROWS: when we can't allocate a user id. add call to check if there's
10089            // enough space to ensure we won't throw; otherwise, don't modify state
10090            mSettings.addUserToSettingLPw(pkgSetting);
10091
10092            if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) {
10093                mTransferedPackages.add(originalPkgSetting.name);
10094            }
10095        }
10096        // TODO(toddke): Consider a method specifically for modifying the Package object
10097        // post scan; or, moving this stuff out of the Package object since it has nothing
10098        // to do with the package on disk.
10099        // We need to have this here because addUserToSettingLPw() is sometimes responsible
10100        // for creating the application ID. If we did this earlier, we would be saving the
10101        // correct ID.
10102        pkg.applicationInfo.uid = pkgSetting.appId;
10103
10104        mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10105
10106        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) {
10107            mTransferedPackages.add(pkg.packageName);
10108        }
10109
10110        // THROWS: when requested libraries that can't be found. it only changes
10111        // the state of the passed in pkg object, so, move to the top of the method
10112        // and allow it to abort
10113        if ((scanFlags & SCAN_BOOTING) == 0
10114                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10115            // Check all shared libraries and map to their actual file path.
10116            // We only do this here for apps not on a system dir, because those
10117            // are the only ones that can fail an install due to this.  We
10118            // will take care of the system apps by updating all of their
10119            // library paths after the scan is done. Also during the initial
10120            // scan don't update any libs as we do this wholesale after all
10121            // apps are scanned to avoid dependency based scanning.
10122            updateSharedLibrariesLPr(pkg, null);
10123        }
10124
10125        // All versions of a static shared library are referenced with the same
10126        // package name. Internally, we use a synthetic package name to allow
10127        // multiple versions of the same shared library to be installed. So,
10128        // we need to generate the synthetic package name of the latest shared
10129        // library in order to compare signatures.
10130        PackageSetting signatureCheckPs = pkgSetting;
10131        if (pkg.applicationInfo.isStaticSharedLibrary()) {
10132            SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10133            if (libraryEntry != null) {
10134                signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10135            }
10136        }
10137
10138        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10139        if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
10140            if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
10141                // We just determined the app is signed correctly, so bring
10142                // over the latest parsed certs.
10143                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10144            } else {
10145                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10146                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10147                            "Package " + pkg.packageName + " upgrade keys do not match the "
10148                                    + "previously installed version");
10149                } else {
10150                    pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10151                    String msg = "System package " + pkg.packageName
10152                            + " signature changed; retaining data.";
10153                    reportSettingsProblem(Log.WARN, msg);
10154                }
10155            }
10156        } else {
10157            try {
10158                final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
10159                final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
10160                final boolean compatMatch = verifySignatures(signatureCheckPs, disabledPkgSetting,
10161                        pkg.mSigningDetails, compareCompat, compareRecover);
10162                // The new KeySets will be re-added later in the scanning process.
10163                if (compatMatch) {
10164                    synchronized (mPackages) {
10165                        ksms.removeAppKeySetDataLPw(pkg.packageName);
10166                    }
10167                }
10168                // We just determined the app is signed correctly, so bring
10169                // over the latest parsed certs.
10170                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10171            } catch (PackageManagerException e) {
10172                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10173                    throw e;
10174                }
10175                // The signature has changed, but this package is in the system
10176                // image...  let's recover!
10177                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10178                // However...  if this package is part of a shared user, but it
10179                // doesn't match the signature of the shared user, let's fail.
10180                // What this means is that you can't change the signatures
10181                // associated with an overall shared user, which doesn't seem all
10182                // that unreasonable.
10183                if (signatureCheckPs.sharedUser != null) {
10184                    if (compareSignatures(
10185                            signatureCheckPs.sharedUser.signatures.mSigningDetails.signatures,
10186                            pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH) {
10187                        throw new PackageManagerException(
10188                                INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10189                                "Signature mismatch for shared user: "
10190                                        + pkgSetting.sharedUser);
10191                    }
10192                }
10193                // File a report about this.
10194                String msg = "System package " + pkg.packageName
10195                        + " signature changed; retaining data.";
10196                reportSettingsProblem(Log.WARN, msg);
10197            }
10198        }
10199
10200        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10201            // This package wants to adopt ownership of permissions from
10202            // another package.
10203            for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10204                final String origName = pkg.mAdoptPermissions.get(i);
10205                final PackageSetting orig = mSettings.getPackageLPr(origName);
10206                if (orig != null) {
10207                    if (verifyPackageUpdateLPr(orig, pkg)) {
10208                        Slog.i(TAG, "Adopting permissions from " + origName + " to "
10209                                + pkg.packageName);
10210                        mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
10211                    }
10212                }
10213            }
10214        }
10215
10216        if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
10217            for (int i = changedAbiCodePath.size() - 1; i <= 0; --i) {
10218                final String codePathString = changedAbiCodePath.get(i);
10219                try {
10220                    mInstaller.rmdex(codePathString,
10221                            getDexCodeInstructionSet(getPreferredInstructionSet()));
10222                } catch (InstallerException ignored) {
10223                }
10224            }
10225        }
10226
10227        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10228            if (oldPkgSetting != null) {
10229                synchronized (mPackages) {
10230                    mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting);
10231                }
10232            }
10233        } else {
10234            final int userId = user == null ? 0 : user.getIdentifier();
10235            // Modify state for the given package setting
10236            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10237                    (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10238            if (pkgSetting.getInstantApp(userId)) {
10239                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10240            }
10241        }
10242    }
10243
10244    /**
10245     * Returns the "real" name of the package.
10246     * <p>This may differ from the package's actual name if the application has already
10247     * been installed under one of this package's original names.
10248     */
10249    private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg,
10250            @Nullable String renamedPkgName) {
10251        if (isPackageRenamed(pkg, renamedPkgName)) {
10252            return pkg.mRealPackage;
10253        }
10254        return null;
10255    }
10256
10257    /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */
10258    private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg,
10259            @Nullable String renamedPkgName) {
10260        return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName);
10261    }
10262
10263    /**
10264     * Returns the original package setting.
10265     * <p>A package can migrate its name during an update. In this scenario, a package
10266     * designates a set of names that it considers as one of its original names.
10267     * <p>An original package must be signed identically and it must have the same
10268     * shared user [if any].
10269     */
10270    @GuardedBy("mPackages")
10271    private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg,
10272            @Nullable String renamedPkgName) {
10273        if (!isPackageRenamed(pkg, renamedPkgName)) {
10274            return null;
10275        }
10276        for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) {
10277            final PackageSetting originalPs =
10278                    mSettings.getPackageLPr(pkg.mOriginalPackages.get(i));
10279            if (originalPs != null) {
10280                // the package is already installed under its original name...
10281                // but, should we use it?
10282                if (!verifyPackageUpdateLPr(originalPs, pkg)) {
10283                    // the new package is incompatible with the original
10284                    continue;
10285                } else if (originalPs.sharedUser != null) {
10286                    if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) {
10287                        // the shared user id is incompatible with the original
10288                        Slog.w(TAG, "Unable to migrate data from " + originalPs.name
10289                                + " to " + pkg.packageName + ": old uid "
10290                                + originalPs.sharedUser.name
10291                                + " differs from " + pkg.mSharedUserId);
10292                        continue;
10293                    }
10294                    // TODO: Add case when shared user id is added [b/28144775]
10295                } else {
10296                    if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10297                            + pkg.packageName + " to old name " + originalPs.name);
10298                }
10299                return originalPs;
10300            }
10301        }
10302        return null;
10303    }
10304
10305    /**
10306     * Renames the package if it was installed under a different name.
10307     * <p>When we've already installed the package under an original name, update
10308     * the new package so we can continue to have the old name.
10309     */
10310    private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg,
10311            @NonNull String renamedPackageName) {
10312        if (pkg.mOriginalPackages == null
10313                || !pkg.mOriginalPackages.contains(renamedPackageName)
10314                || pkg.packageName.equals(renamedPackageName)) {
10315            return;
10316        }
10317        pkg.setPackageName(renamedPackageName);
10318    }
10319
10320    /**
10321     * Just scans the package without any side effects.
10322     * <p>Not entirely true at the moment. There is still one side effect -- this
10323     * method potentially modifies a live {@link PackageSetting} object representing
10324     * the package being scanned. This will be resolved in the future.
10325     *
10326     * @param request Information about the package to be scanned
10327     * @param isUnderFactoryTest Whether or not the device is under factory test
10328     * @param currentTime The current time, in millis
10329     * @return The results of the scan
10330     */
10331    @GuardedBy("mInstallLock")
10332    private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request,
10333            boolean isUnderFactoryTest, long currentTime)
10334                    throws PackageManagerException {
10335        final PackageParser.Package pkg = request.pkg;
10336        PackageSetting pkgSetting = request.pkgSetting;
10337        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10338        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10339        final @ParseFlags int parseFlags = request.parseFlags;
10340        final @ScanFlags int scanFlags = request.scanFlags;
10341        final String realPkgName = request.realPkgName;
10342        final SharedUserSetting sharedUserSetting = request.sharedUserSetting;
10343        final UserHandle user = request.user;
10344        final boolean isPlatformPackage = request.isPlatformPackage;
10345
10346        List<String> changedAbiCodePath = null;
10347
10348        if (DEBUG_PACKAGE_SCANNING) {
10349            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10350                Log.d(TAG, "Scanning package " + pkg.packageName);
10351        }
10352
10353        if (Build.IS_DEBUGGABLE &&
10354                pkg.isPrivileged() &&
10355                !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) {
10356            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10357        }
10358
10359        // Initialize package source and resource directories
10360        final File scanFile = new File(pkg.codePath);
10361        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10362        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10363
10364        // We keep references to the derived CPU Abis from settings in oder to reuse
10365        // them in the case where we're not upgrading or booting for the first time.
10366        String primaryCpuAbiFromSettings = null;
10367        String secondaryCpuAbiFromSettings = null;
10368        boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0;
10369
10370        if (!needToDeriveAbi) {
10371            if (pkgSetting != null) {
10372                primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString;
10373                secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString;
10374            } else {
10375                // Re-scanning a system package after uninstalling updates; need to derive ABI
10376                needToDeriveAbi = true;
10377            }
10378        }
10379
10380        if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) {
10381            PackageManagerService.reportSettingsProblem(Log.WARN,
10382                    "Package " + pkg.packageName + " shared user changed from "
10383                            + (pkgSetting.sharedUser != null
10384                            ? pkgSetting.sharedUser.name : "<nothing>")
10385                            + " to "
10386                            + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>")
10387                            + "; replacing with new");
10388            pkgSetting = null;
10389        }
10390
10391        String[] usesStaticLibraries = null;
10392        if (pkg.usesStaticLibraries != null) {
10393            usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10394            pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10395        }
10396        final boolean createNewPackage = (pkgSetting == null);
10397        if (createNewPackage) {
10398            final String parentPackageName = (pkg.parentPackage != null)
10399                    ? pkg.parentPackage.packageName : null;
10400            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10401            final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10402            // REMOVE SharedUserSetting from method; update in a separate call
10403            pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting,
10404                    disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile,
10405                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
10406                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10407                    pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10408                    user, true /*allowInstall*/, instantApp, virtualPreload,
10409                    parentPackageName, pkg.getChildPackageNames(),
10410                    UserManagerService.getInstance(), usesStaticLibraries,
10411                    pkg.usesStaticLibrariesVersions);
10412        } else {
10413            // REMOVE SharedUserSetting from method; update in a separate call.
10414            //
10415            // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10416            // secondaryCpuAbi are not known at this point so we always update them
10417            // to null here, only to reset them at a later point.
10418            Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting,
10419                    destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir,
10420                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10421                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10422                    pkg.getChildPackageNames(), UserManagerService.getInstance(),
10423                    usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10424        }
10425        if (createNewPackage && originalPkgSetting != null) {
10426            // This is the initial transition from the original package, so,
10427            // fix up the new package's name now. We must do this after looking
10428            // up the package under its new name, so getPackageLP takes care of
10429            // fiddling things correctly.
10430            pkg.setPackageName(originalPkgSetting.name);
10431
10432            // File a report about this.
10433            String msg = "New package " + pkgSetting.realName
10434                    + " renamed to replace old package " + pkgSetting.name;
10435            reportSettingsProblem(Log.WARN, msg);
10436        }
10437
10438        if (disabledPkgSetting != null) {
10439            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10440        }
10441
10442        // SELinux sandboxes become more restrictive as targetSdkVersion increases.
10443        // To ensure that apps with sharedUserId are placed in the same selinux domain
10444        // without breaking any assumptions about access, put them into the least
10445        // restrictive targetSdkVersion=25 domain.
10446        // TODO(b/72290969): Base this on the actual targetSdkVersion(s) of the apps within the
10447        // sharedUserSetting, instead of defaulting to the least restrictive domain.
10448        final int targetSdk = (sharedUserSetting != null) ? 25
10449                : pkg.applicationInfo.targetSdkVersion;
10450        // TODO(b/71593002): isPrivileged for sharedUser and appInfo should never be out of sync.
10451        // They currently can be if the sharedUser apps are signed with the platform key.
10452        final boolean isPrivileged = (sharedUserSetting != null) ? sharedUserSetting.isPrivileged()
10453                : pkg.applicationInfo.isPrivilegedApp();
10454        SELinuxMMAC.assignSeInfoValue(pkg, isPrivileged, targetSdk);
10455
10456        pkg.mExtras = pkgSetting;
10457        pkg.applicationInfo.processName = fixProcessName(
10458                pkg.applicationInfo.packageName,
10459                pkg.applicationInfo.processName);
10460
10461        if (!isPlatformPackage) {
10462            // Get all of our default paths setup
10463            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10464        }
10465
10466        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10467
10468        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10469            if (needToDeriveAbi) {
10470                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10471                final boolean extractNativeLibs = !pkg.isLibrary();
10472                derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs);
10473                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10474
10475                // Some system apps still use directory structure for native libraries
10476                // in which case we might end up not detecting abi solely based on apk
10477                // structure. Try to detect abi based on directory structure.
10478                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10479                        pkg.applicationInfo.primaryCpuAbi == null) {
10480                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10481                    setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10482                }
10483            } else {
10484                // This is not a first boot or an upgrade, don't bother deriving the
10485                // ABI during the scan. Instead, trust the value that was stored in the
10486                // package setting.
10487                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10488                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10489
10490                setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10491
10492                if (DEBUG_ABI_SELECTION) {
10493                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10494                            pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10495                            pkg.applicationInfo.secondaryCpuAbi);
10496                }
10497            }
10498        } else {
10499            if ((scanFlags & SCAN_MOVE) != 0) {
10500                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10501                // but we already have this packages package info in the PackageSetting. We just
10502                // use that and derive the native library path based on the new codepath.
10503                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10504                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10505            }
10506
10507            // Set native library paths again. For moves, the path will be updated based on the
10508            // ABIs we've determined above. For non-moves, the path will be updated based on the
10509            // ABIs we determined during compilation, but the path will depend on the final
10510            // package path (after the rename away from the stage path).
10511            setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10512        }
10513
10514        // This is a special case for the "system" package, where the ABI is
10515        // dictated by the zygote configuration (and init.rc). We should keep track
10516        // of this ABI so that we can deal with "normal" applications that run under
10517        // the same UID correctly.
10518        if (isPlatformPackage) {
10519            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10520                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10521        }
10522
10523        // If there's a mismatch between the abi-override in the package setting
10524        // and the abiOverride specified for the install. Warn about this because we
10525        // would've already compiled the app without taking the package setting into
10526        // account.
10527        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10528            if (cpuAbiOverride == null && pkg.packageName != null) {
10529                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10530                        " for package " + pkg.packageName);
10531            }
10532        }
10533
10534        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10535        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10536        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10537
10538        // Copy the derived override back to the parsed package, so that we can
10539        // update the package settings accordingly.
10540        pkg.cpuAbiOverride = cpuAbiOverride;
10541
10542        if (DEBUG_ABI_SELECTION) {
10543            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName
10544                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10545                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10546        }
10547
10548        // Push the derived path down into PackageSettings so we know what to
10549        // clean up at uninstall time.
10550        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10551
10552        if (DEBUG_ABI_SELECTION) {
10553            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10554                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10555                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10556        }
10557
10558        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10559            // We don't do this here during boot because we can do it all
10560            // at once after scanning all existing packages.
10561            //
10562            // We also do this *before* we perform dexopt on this package, so that
10563            // we can avoid redundant dexopts, and also to make sure we've got the
10564            // code and package path correct.
10565            changedAbiCodePath =
10566                    adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10567        }
10568
10569        if (isUnderFactoryTest && pkg.requestedPermissions.contains(
10570                android.Manifest.permission.FACTORY_TEST)) {
10571            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10572        }
10573
10574        if (isSystemApp(pkg)) {
10575            pkgSetting.isOrphaned = true;
10576        }
10577
10578        // Take care of first install / last update times.
10579        final long scanFileTime = getLastModifiedTime(pkg);
10580        if (currentTime != 0) {
10581            if (pkgSetting.firstInstallTime == 0) {
10582                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10583            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10584                pkgSetting.lastUpdateTime = currentTime;
10585            }
10586        } else if (pkgSetting.firstInstallTime == 0) {
10587            // We need *something*.  Take time time stamp of the file.
10588            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10589        } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10590            if (scanFileTime != pkgSetting.timeStamp) {
10591                // A package on the system image has changed; consider this
10592                // to be an update.
10593                pkgSetting.lastUpdateTime = scanFileTime;
10594            }
10595        }
10596        pkgSetting.setTimeStamp(scanFileTime);
10597
10598        pkgSetting.pkg = pkg;
10599        pkgSetting.pkgFlags = pkg.applicationInfo.flags;
10600        if (pkg.getLongVersionCode() != pkgSetting.versionCode) {
10601            pkgSetting.versionCode = pkg.getLongVersionCode();
10602        }
10603        // Update volume if needed
10604        final String volumeUuid = pkg.applicationInfo.volumeUuid;
10605        if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) {
10606            Slog.i(PackageManagerService.TAG,
10607                    "Update" + (pkgSetting.isSystem() ? " system" : "")
10608                    + " package " + pkg.packageName
10609                    + " volume from " + pkgSetting.volumeUuid
10610                    + " to " + volumeUuid);
10611            pkgSetting.volumeUuid = volumeUuid;
10612        }
10613
10614        return new ScanResult(true, pkgSetting, changedAbiCodePath);
10615    }
10616
10617    /**
10618     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10619     */
10620    private static boolean apkHasCode(String fileName) {
10621        StrictJarFile jarFile = null;
10622        try {
10623            jarFile = new StrictJarFile(fileName,
10624                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10625            return jarFile.findEntry("classes.dex") != null;
10626        } catch (IOException ignore) {
10627        } finally {
10628            try {
10629                if (jarFile != null) {
10630                    jarFile.close();
10631                }
10632            } catch (IOException ignore) {}
10633        }
10634        return false;
10635    }
10636
10637    /**
10638     * Enforces code policy for the package. This ensures that if an APK has
10639     * declared hasCode="true" in its manifest that the APK actually contains
10640     * code.
10641     *
10642     * @throws PackageManagerException If bytecode could not be found when it should exist
10643     */
10644    private static void assertCodePolicy(PackageParser.Package pkg)
10645            throws PackageManagerException {
10646        final boolean shouldHaveCode =
10647                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10648        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10649            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10650                    "Package " + pkg.baseCodePath + " code is missing");
10651        }
10652
10653        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10654            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10655                final boolean splitShouldHaveCode =
10656                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10657                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10658                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10659                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10660                }
10661            }
10662        }
10663    }
10664
10665    /**
10666     * Applies policy to the parsed package based upon the given policy flags.
10667     * Ensures the package is in a good state.
10668     * <p>
10669     * Implementation detail: This method must NOT have any side effect. It would
10670     * ideally be static, but, it requires locks to read system state.
10671     */
10672    private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10673            final @ScanFlags int scanFlags) {
10674        if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10675            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10676            if (pkg.applicationInfo.isDirectBootAware()) {
10677                // we're direct boot aware; set for all components
10678                for (PackageParser.Service s : pkg.services) {
10679                    s.info.encryptionAware = s.info.directBootAware = true;
10680                }
10681                for (PackageParser.Provider p : pkg.providers) {
10682                    p.info.encryptionAware = p.info.directBootAware = true;
10683                }
10684                for (PackageParser.Activity a : pkg.activities) {
10685                    a.info.encryptionAware = a.info.directBootAware = true;
10686                }
10687                for (PackageParser.Activity r : pkg.receivers) {
10688                    r.info.encryptionAware = r.info.directBootAware = true;
10689                }
10690            }
10691            if (compressedFileExists(pkg.codePath)) {
10692                pkg.isStub = true;
10693            }
10694        } else {
10695            // non system apps can't be flagged as core
10696            pkg.coreApp = false;
10697            // clear flags not applicable to regular apps
10698            pkg.applicationInfo.flags &=
10699                    ~ApplicationInfo.FLAG_PERSISTENT;
10700            pkg.applicationInfo.privateFlags &=
10701                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10702            pkg.applicationInfo.privateFlags &=
10703                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10704            // clear protected broadcasts
10705            pkg.protectedBroadcasts = null;
10706            // cap permission priorities
10707            if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) {
10708                for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) {
10709                    pkg.permissionGroups.get(i).info.priority = 0;
10710                }
10711            }
10712        }
10713        if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10714            // ignore export request for single user receivers
10715            if (pkg.receivers != null) {
10716                for (int i = pkg.receivers.size() - 1; i >= 0; --i) {
10717                    final PackageParser.Activity receiver = pkg.receivers.get(i);
10718                    if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) {
10719                        receiver.info.exported = false;
10720                    }
10721                }
10722            }
10723            // ignore export request for single user services
10724            if (pkg.services != null) {
10725                for (int i = pkg.services.size() - 1; i >= 0; --i) {
10726                    final PackageParser.Service service = pkg.services.get(i);
10727                    if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
10728                        service.info.exported = false;
10729                    }
10730                }
10731            }
10732            // ignore export request for single user providers
10733            if (pkg.providers != null) {
10734                for (int i = pkg.providers.size() - 1; i >= 0; --i) {
10735                    final PackageParser.Provider provider = pkg.providers.get(i);
10736                    if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) {
10737                        provider.info.exported = false;
10738                    }
10739                }
10740            }
10741        }
10742
10743        if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) {
10744            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10745        }
10746
10747        if ((scanFlags & SCAN_AS_OEM) != 0) {
10748            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10749        }
10750
10751        if ((scanFlags & SCAN_AS_VENDOR) != 0) {
10752            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR;
10753        }
10754
10755        if ((scanFlags & SCAN_AS_PRODUCT) != 0) {
10756            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRODUCT;
10757        }
10758
10759        if (!isSystemApp(pkg)) {
10760            // Only system apps can use these features.
10761            pkg.mOriginalPackages = null;
10762            pkg.mRealPackage = null;
10763            pkg.mAdoptPermissions = null;
10764        }
10765    }
10766
10767    private static @NonNull <T> T assertNotNull(@Nullable T object, String message)
10768            throws PackageManagerException {
10769        if (object == null) {
10770            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, message);
10771        }
10772        return object;
10773    }
10774
10775    /**
10776     * Asserts the parsed package is valid according to the given policy. If the
10777     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10778     * <p>
10779     * Implementation detail: This method must NOT have any side effects. It would
10780     * ideally be static, but, it requires locks to read system state.
10781     *
10782     * @throws PackageManagerException If the package fails any of the validation checks
10783     */
10784    private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10785            final @ScanFlags int scanFlags)
10786                    throws PackageManagerException {
10787        if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10788            assertCodePolicy(pkg);
10789        }
10790
10791        if (pkg.applicationInfo.getCodePath() == null ||
10792                pkg.applicationInfo.getResourcePath() == null) {
10793            // Bail out. The resource and code paths haven't been set.
10794            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10795                    "Code and resource paths haven't been set correctly");
10796        }
10797
10798        // Make sure we're not adding any bogus keyset info
10799        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10800        ksms.assertScannedPackageValid(pkg);
10801
10802        synchronized (mPackages) {
10803            // The special "android" package can only be defined once
10804            if (pkg.packageName.equals("android")) {
10805                if (mAndroidApplication != null) {
10806                    Slog.w(TAG, "*************************************************");
10807                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10808                    Slog.w(TAG, " codePath=" + pkg.codePath);
10809                    Slog.w(TAG, "*************************************************");
10810                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10811                            "Core android package being redefined.  Skipping.");
10812                }
10813            }
10814
10815            // A package name must be unique; don't allow duplicates
10816            if (mPackages.containsKey(pkg.packageName)) {
10817                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10818                        "Application package " + pkg.packageName
10819                        + " already installed.  Skipping duplicate.");
10820            }
10821
10822            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10823                // Static libs have a synthetic package name containing the version
10824                // but we still want the base name to be unique.
10825                if (mPackages.containsKey(pkg.manifestPackageName)) {
10826                    throw new PackageManagerException(
10827                            "Duplicate static shared lib provider package");
10828                }
10829
10830                // Static shared libraries should have at least O target SDK
10831                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10832                    throw new PackageManagerException(
10833                            "Packages declaring static-shared libs must target O SDK or higher");
10834                }
10835
10836                // Package declaring static a shared lib cannot be instant apps
10837                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10838                    throw new PackageManagerException(
10839                            "Packages declaring static-shared libs cannot be instant apps");
10840                }
10841
10842                // Package declaring static a shared lib cannot be renamed since the package
10843                // name is synthetic and apps can't code around package manager internals.
10844                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10845                    throw new PackageManagerException(
10846                            "Packages declaring static-shared libs cannot be renamed");
10847                }
10848
10849                // Package declaring static a shared lib cannot declare child packages
10850                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10851                    throw new PackageManagerException(
10852                            "Packages declaring static-shared libs cannot have child packages");
10853                }
10854
10855                // Package declaring static a shared lib cannot declare dynamic libs
10856                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10857                    throw new PackageManagerException(
10858                            "Packages declaring static-shared libs cannot declare dynamic libs");
10859                }
10860
10861                // Package declaring static a shared lib cannot declare shared users
10862                if (pkg.mSharedUserId != null) {
10863                    throw new PackageManagerException(
10864                            "Packages declaring static-shared libs cannot declare shared users");
10865                }
10866
10867                // Static shared libs cannot declare activities
10868                if (!pkg.activities.isEmpty()) {
10869                    throw new PackageManagerException(
10870                            "Static shared libs cannot declare activities");
10871                }
10872
10873                // Static shared libs cannot declare services
10874                if (!pkg.services.isEmpty()) {
10875                    throw new PackageManagerException(
10876                            "Static shared libs cannot declare services");
10877                }
10878
10879                // Static shared libs cannot declare providers
10880                if (!pkg.providers.isEmpty()) {
10881                    throw new PackageManagerException(
10882                            "Static shared libs cannot declare content providers");
10883                }
10884
10885                // Static shared libs cannot declare receivers
10886                if (!pkg.receivers.isEmpty()) {
10887                    throw new PackageManagerException(
10888                            "Static shared libs cannot declare broadcast receivers");
10889                }
10890
10891                // Static shared libs cannot declare permission groups
10892                if (!pkg.permissionGroups.isEmpty()) {
10893                    throw new PackageManagerException(
10894                            "Static shared libs cannot declare permission groups");
10895                }
10896
10897                // Static shared libs cannot declare permissions
10898                if (!pkg.permissions.isEmpty()) {
10899                    throw new PackageManagerException(
10900                            "Static shared libs cannot declare permissions");
10901                }
10902
10903                // Static shared libs cannot declare protected broadcasts
10904                if (pkg.protectedBroadcasts != null) {
10905                    throw new PackageManagerException(
10906                            "Static shared libs cannot declare protected broadcasts");
10907                }
10908
10909                // Static shared libs cannot be overlay targets
10910                if (pkg.mOverlayTarget != null) {
10911                    throw new PackageManagerException(
10912                            "Static shared libs cannot be overlay targets");
10913                }
10914
10915                // The version codes must be ordered as lib versions
10916                long minVersionCode = Long.MIN_VALUE;
10917                long maxVersionCode = Long.MAX_VALUE;
10918
10919                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10920                        pkg.staticSharedLibName);
10921                if (versionedLib != null) {
10922                    final int versionCount = versionedLib.size();
10923                    for (int i = 0; i < versionCount; i++) {
10924                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10925                        final long libVersionCode = libInfo.getDeclaringPackage()
10926                                .getLongVersionCode();
10927                        if (libInfo.getLongVersion() <  pkg.staticSharedLibVersion) {
10928                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10929                        } else if (libInfo.getLongVersion() >  pkg.staticSharedLibVersion) {
10930                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10931                        } else {
10932                            minVersionCode = maxVersionCode = libVersionCode;
10933                            break;
10934                        }
10935                    }
10936                }
10937                if (pkg.getLongVersionCode() < minVersionCode
10938                        || pkg.getLongVersionCode() > maxVersionCode) {
10939                    throw new PackageManagerException("Static shared"
10940                            + " lib version codes must be ordered as lib versions");
10941                }
10942            }
10943
10944            // Only privileged apps and updated privileged apps can add child packages.
10945            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10946                if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10947                    throw new PackageManagerException("Only privileged apps can add child "
10948                            + "packages. Ignoring package " + pkg.packageName);
10949                }
10950                final int childCount = pkg.childPackages.size();
10951                for (int i = 0; i < childCount; i++) {
10952                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10953                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10954                            childPkg.packageName)) {
10955                        throw new PackageManagerException("Can't override child of "
10956                                + "another disabled app. Ignoring package " + pkg.packageName);
10957                    }
10958                }
10959            }
10960
10961            // If we're only installing presumed-existing packages, require that the
10962            // scanned APK is both already known and at the path previously established
10963            // for it.  Previously unknown packages we pick up normally, but if we have an
10964            // a priori expectation about this package's install presence, enforce it.
10965            // With a singular exception for new system packages. When an OTA contains
10966            // a new system package, we allow the codepath to change from a system location
10967            // to the user-installed location. If we don't allow this change, any newer,
10968            // user-installed version of the application will be ignored.
10969            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10970                if (mExpectingBetter.containsKey(pkg.packageName)) {
10971                    logCriticalInfo(Log.WARN,
10972                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10973                } else {
10974                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10975                    if (known != null) {
10976                        if (DEBUG_PACKAGE_SCANNING) {
10977                            Log.d(TAG, "Examining " + pkg.codePath
10978                                    + " and requiring known paths " + known.codePathString
10979                                    + " & " + known.resourcePathString);
10980                        }
10981                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10982                                || !pkg.applicationInfo.getResourcePath().equals(
10983                                        known.resourcePathString)) {
10984                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10985                                    "Application package " + pkg.packageName
10986                                    + " found at " + pkg.applicationInfo.getCodePath()
10987                                    + " but expected at " + known.codePathString
10988                                    + "; ignoring.");
10989                        }
10990                    } else {
10991                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10992                                "Application package " + pkg.packageName
10993                                + " not found; ignoring.");
10994                    }
10995                }
10996            }
10997
10998            // Verify that this new package doesn't have any content providers
10999            // that conflict with existing packages.  Only do this if the
11000            // package isn't already installed, since we don't want to break
11001            // things that are installed.
11002            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11003                final int N = pkg.providers.size();
11004                int i;
11005                for (i=0; i<N; i++) {
11006                    PackageParser.Provider p = pkg.providers.get(i);
11007                    if (p.info.authority != null) {
11008                        String names[] = p.info.authority.split(";");
11009                        for (int j = 0; j < names.length; j++) {
11010                            if (mProvidersByAuthority.containsKey(names[j])) {
11011                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11012                                final String otherPackageName =
11013                                        ((other != null && other.getComponentName() != null) ?
11014                                                other.getComponentName().getPackageName() : "?");
11015                                throw new PackageManagerException(
11016                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11017                                        "Can't install because provider name " + names[j]
11018                                                + " (in package " + pkg.applicationInfo.packageName
11019                                                + ") is already used by " + otherPackageName);
11020                            }
11021                        }
11022                    }
11023                }
11024            }
11025
11026            // Verify that packages sharing a user with a privileged app are marked as privileged.
11027            if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) {
11028                SharedUserSetting sharedUserSetting = null;
11029                try {
11030                    sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
11031                } catch (PackageManagerException ignore) {}
11032                if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
11033                    // Exempt SharedUsers signed with the platform key.
11034                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
11035                    if ((platformPkgSetting.signatures.mSigningDetails
11036                            != PackageParser.SigningDetails.UNKNOWN)
11037                            && (compareSignatures(
11038                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11039                                    pkg.mSigningDetails.signatures)
11040                                            != PackageManager.SIGNATURE_MATCH)) {
11041                        throw new PackageManagerException("Apps that share a user with a " +
11042                                "privileged app must themselves be marked as privileged. " +
11043                                pkg.packageName + " shares privileged user " +
11044                                pkg.mSharedUserId + ".");
11045                    }
11046                }
11047            }
11048
11049            // Apply policies specific for runtime resource overlays (RROs).
11050            if (pkg.mOverlayTarget != null) {
11051                // System overlays have some restrictions on their use of the 'static' state.
11052                if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
11053                    // We are scanning a system overlay. This can be the first scan of the
11054                    // system/vendor/oem partition, or an update to the system overlay.
11055                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
11056                        // This must be an update to a system overlay.
11057                        final PackageSetting previousPkg = assertNotNull(
11058                                mSettings.getPackageLPr(pkg.packageName),
11059                                "previous package state not present");
11060
11061                        // Static overlays cannot be updated.
11062                        if (previousPkg.pkg.mOverlayIsStatic) {
11063                            throw new PackageManagerException("Overlay " + pkg.packageName +
11064                                    " is static and cannot be upgraded.");
11065                        // Non-static overlays cannot be converted to static overlays.
11066                        } else if (pkg.mOverlayIsStatic) {
11067                            throw new PackageManagerException("Overlay " + pkg.packageName +
11068                                    " cannot be upgraded into a static overlay.");
11069                        }
11070                    }
11071                } else {
11072                    // The overlay is a non-system overlay. Non-system overlays cannot be static.
11073                    if (pkg.mOverlayIsStatic) {
11074                        throw new PackageManagerException("Overlay " + pkg.packageName +
11075                                " is static but not pre-installed.");
11076                    }
11077
11078                    // The only case where we allow installation of a non-system overlay is when
11079                    // its signature is signed with the platform certificate.
11080                    PackageSetting platformPkgSetting = mSettings.getPackageLPr("android");
11081                    if ((platformPkgSetting.signatures.mSigningDetails
11082                            != PackageParser.SigningDetails.UNKNOWN)
11083                            && (compareSignatures(
11084                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11085                                    pkg.mSigningDetails.signatures)
11086                                            != PackageManager.SIGNATURE_MATCH)) {
11087                        throw new PackageManagerException("Overlay " + pkg.packageName +
11088                                " must be signed with the platform certificate.");
11089                    }
11090                }
11091            }
11092        }
11093    }
11094
11095    private boolean addSharedLibraryLPw(String path, String apk, String name, long version,
11096            int type, String declaringPackageName, long declaringVersionCode) {
11097        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11098        if (versionedLib == null) {
11099            versionedLib = new LongSparseArray<>();
11100            mSharedLibraries.put(name, versionedLib);
11101            if (type == SharedLibraryInfo.TYPE_STATIC) {
11102                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11103            }
11104        } else if (versionedLib.indexOfKey(version) >= 0) {
11105            return false;
11106        }
11107        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11108                version, type, declaringPackageName, declaringVersionCode);
11109        versionedLib.put(version, libEntry);
11110        return true;
11111    }
11112
11113    private boolean removeSharedLibraryLPw(String name, long version) {
11114        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11115        if (versionedLib == null) {
11116            return false;
11117        }
11118        final int libIdx = versionedLib.indexOfKey(version);
11119        if (libIdx < 0) {
11120            return false;
11121        }
11122        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11123        versionedLib.remove(version);
11124        if (versionedLib.size() <= 0) {
11125            mSharedLibraries.remove(name);
11126            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11127                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11128                        .getPackageName());
11129            }
11130        }
11131        return true;
11132    }
11133
11134    /**
11135     * Adds a scanned package to the system. When this method is finished, the package will
11136     * be available for query, resolution, etc...
11137     */
11138    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11139            UserHandle user, final @ScanFlags int scanFlags, boolean chatty) {
11140        final String pkgName = pkg.packageName;
11141        if (mCustomResolverComponentName != null &&
11142                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11143            setUpCustomResolverActivity(pkg);
11144        }
11145
11146        if (pkg.packageName.equals("android")) {
11147            synchronized (mPackages) {
11148                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11149                    // Set up information for our fall-back user intent resolution activity.
11150                    mPlatformPackage = pkg;
11151                    pkg.mVersionCode = mSdkVersion;
11152                    pkg.mVersionCodeMajor = 0;
11153                    mAndroidApplication = pkg.applicationInfo;
11154                    if (!mResolverReplaced) {
11155                        mResolveActivity.applicationInfo = mAndroidApplication;
11156                        mResolveActivity.name = ResolverActivity.class.getName();
11157                        mResolveActivity.packageName = mAndroidApplication.packageName;
11158                        mResolveActivity.processName = "system:ui";
11159                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11160                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11161                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11162                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11163                        mResolveActivity.exported = true;
11164                        mResolveActivity.enabled = true;
11165                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11166                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11167                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11168                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11169                                | ActivityInfo.CONFIG_ORIENTATION
11170                                | ActivityInfo.CONFIG_KEYBOARD
11171                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11172                        mResolveInfo.activityInfo = mResolveActivity;
11173                        mResolveInfo.priority = 0;
11174                        mResolveInfo.preferredOrder = 0;
11175                        mResolveInfo.match = 0;
11176                        mResolveComponentName = new ComponentName(
11177                                mAndroidApplication.packageName, mResolveActivity.name);
11178                    }
11179                }
11180            }
11181        }
11182
11183        ArrayList<PackageParser.Package> clientLibPkgs = null;
11184        // writer
11185        synchronized (mPackages) {
11186            boolean hasStaticSharedLibs = false;
11187
11188            // Any app can add new static shared libraries
11189            if (pkg.staticSharedLibName != null) {
11190                // Static shared libs don't allow renaming as they have synthetic package
11191                // names to allow install of multiple versions, so use name from manifest.
11192                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11193                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11194                        pkg.manifestPackageName, pkg.getLongVersionCode())) {
11195                    hasStaticSharedLibs = true;
11196                } else {
11197                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11198                                + pkg.staticSharedLibName + " already exists; skipping");
11199                }
11200                // Static shared libs cannot be updated once installed since they
11201                // use synthetic package name which includes the version code, so
11202                // not need to update other packages's shared lib dependencies.
11203            }
11204
11205            if (!hasStaticSharedLibs
11206                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11207                // Only system apps can add new dynamic shared libraries.
11208                if (pkg.libraryNames != null) {
11209                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11210                        String name = pkg.libraryNames.get(i);
11211                        boolean allowed = false;
11212                        if (pkg.isUpdatedSystemApp()) {
11213                            // New library entries can only be added through the
11214                            // system image.  This is important to get rid of a lot
11215                            // of nasty edge cases: for example if we allowed a non-
11216                            // system update of the app to add a library, then uninstalling
11217                            // the update would make the library go away, and assumptions
11218                            // we made such as through app install filtering would now
11219                            // have allowed apps on the device which aren't compatible
11220                            // with it.  Better to just have the restriction here, be
11221                            // conservative, and create many fewer cases that can negatively
11222                            // impact the user experience.
11223                            final PackageSetting sysPs = mSettings
11224                                    .getDisabledSystemPkgLPr(pkg.packageName);
11225                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11226                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11227                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11228                                        allowed = true;
11229                                        break;
11230                                    }
11231                                }
11232                            }
11233                        } else {
11234                            allowed = true;
11235                        }
11236                        if (allowed) {
11237                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11238                                    SharedLibraryInfo.VERSION_UNDEFINED,
11239                                    SharedLibraryInfo.TYPE_DYNAMIC,
11240                                    pkg.packageName, pkg.getLongVersionCode())) {
11241                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11242                                        + name + " already exists; skipping");
11243                            }
11244                        } else {
11245                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11246                                    + name + " that is not declared on system image; skipping");
11247                        }
11248                    }
11249
11250                    if ((scanFlags & SCAN_BOOTING) == 0) {
11251                        // If we are not booting, we need to update any applications
11252                        // that are clients of our shared library.  If we are booting,
11253                        // this will all be done once the scan is complete.
11254                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11255                    }
11256                }
11257            }
11258        }
11259
11260        if ((scanFlags & SCAN_BOOTING) != 0) {
11261            // No apps can run during boot scan, so they don't need to be frozen
11262        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11263            // Caller asked to not kill app, so it's probably not frozen
11264        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11265            // Caller asked us to ignore frozen check for some reason; they
11266            // probably didn't know the package name
11267        } else {
11268            // We're doing major surgery on this package, so it better be frozen
11269            // right now to keep it from launching
11270            checkPackageFrozen(pkgName);
11271        }
11272
11273        // Also need to kill any apps that are dependent on the library.
11274        if (clientLibPkgs != null) {
11275            for (int i=0; i<clientLibPkgs.size(); i++) {
11276                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11277                killApplication(clientPkg.applicationInfo.packageName,
11278                        clientPkg.applicationInfo.uid, "update lib");
11279            }
11280        }
11281
11282        // writer
11283        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11284
11285        synchronized (mPackages) {
11286            // We don't expect installation to fail beyond this point
11287
11288            // Add the new setting to mSettings
11289            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11290            // Add the new setting to mPackages
11291            mPackages.put(pkg.applicationInfo.packageName, pkg);
11292            // Make sure we don't accidentally delete its data.
11293            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11294            while (iter.hasNext()) {
11295                PackageCleanItem item = iter.next();
11296                if (pkgName.equals(item.packageName)) {
11297                    iter.remove();
11298                }
11299            }
11300
11301            // Add the package's KeySets to the global KeySetManagerService
11302            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11303            ksms.addScannedPackageLPw(pkg);
11304
11305            int N = pkg.providers.size();
11306            StringBuilder r = null;
11307            int i;
11308            for (i=0; i<N; i++) {
11309                PackageParser.Provider p = pkg.providers.get(i);
11310                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11311                        p.info.processName);
11312                mProviders.addProvider(p);
11313                p.syncable = p.info.isSyncable;
11314                if (p.info.authority != null) {
11315                    String names[] = p.info.authority.split(";");
11316                    p.info.authority = null;
11317                    for (int j = 0; j < names.length; j++) {
11318                        if (j == 1 && p.syncable) {
11319                            // We only want the first authority for a provider to possibly be
11320                            // syncable, so if we already added this provider using a different
11321                            // authority clear the syncable flag. We copy the provider before
11322                            // changing it because the mProviders object contains a reference
11323                            // to a provider that we don't want to change.
11324                            // Only do this for the second authority since the resulting provider
11325                            // object can be the same for all future authorities for this provider.
11326                            p = new PackageParser.Provider(p);
11327                            p.syncable = false;
11328                        }
11329                        if (!mProvidersByAuthority.containsKey(names[j])) {
11330                            mProvidersByAuthority.put(names[j], p);
11331                            if (p.info.authority == null) {
11332                                p.info.authority = names[j];
11333                            } else {
11334                                p.info.authority = p.info.authority + ";" + names[j];
11335                            }
11336                            if (DEBUG_PACKAGE_SCANNING) {
11337                                if (chatty)
11338                                    Log.d(TAG, "Registered content provider: " + names[j]
11339                                            + ", className = " + p.info.name + ", isSyncable = "
11340                                            + p.info.isSyncable);
11341                            }
11342                        } else {
11343                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11344                            Slog.w(TAG, "Skipping provider name " + names[j] +
11345                                    " (in package " + pkg.applicationInfo.packageName +
11346                                    "): name already used by "
11347                                    + ((other != null && other.getComponentName() != null)
11348                                            ? other.getComponentName().getPackageName() : "?"));
11349                        }
11350                    }
11351                }
11352                if (chatty) {
11353                    if (r == null) {
11354                        r = new StringBuilder(256);
11355                    } else {
11356                        r.append(' ');
11357                    }
11358                    r.append(p.info.name);
11359                }
11360            }
11361            if (r != null) {
11362                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11363            }
11364
11365            N = pkg.services.size();
11366            r = null;
11367            for (i=0; i<N; i++) {
11368                PackageParser.Service s = pkg.services.get(i);
11369                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11370                        s.info.processName);
11371                mServices.addService(s);
11372                if (chatty) {
11373                    if (r == null) {
11374                        r = new StringBuilder(256);
11375                    } else {
11376                        r.append(' ');
11377                    }
11378                    r.append(s.info.name);
11379                }
11380            }
11381            if (r != null) {
11382                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11383            }
11384
11385            N = pkg.receivers.size();
11386            r = null;
11387            for (i=0; i<N; i++) {
11388                PackageParser.Activity a = pkg.receivers.get(i);
11389                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11390                        a.info.processName);
11391                mReceivers.addActivity(a, "receiver");
11392                if (chatty) {
11393                    if (r == null) {
11394                        r = new StringBuilder(256);
11395                    } else {
11396                        r.append(' ');
11397                    }
11398                    r.append(a.info.name);
11399                }
11400            }
11401            if (r != null) {
11402                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11403            }
11404
11405            N = pkg.activities.size();
11406            r = null;
11407            for (i=0; i<N; i++) {
11408                PackageParser.Activity a = pkg.activities.get(i);
11409                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11410                        a.info.processName);
11411                mActivities.addActivity(a, "activity");
11412                if (chatty) {
11413                    if (r == null) {
11414                        r = new StringBuilder(256);
11415                    } else {
11416                        r.append(' ');
11417                    }
11418                    r.append(a.info.name);
11419                }
11420            }
11421            if (r != null) {
11422                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11423            }
11424
11425            // Don't allow ephemeral applications to define new permissions groups.
11426            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11427                Slog.w(TAG, "Permission groups from package " + pkg.packageName
11428                        + " ignored: instant apps cannot define new permission groups.");
11429            } else {
11430                mPermissionManager.addAllPermissionGroups(pkg, chatty);
11431            }
11432
11433            // Don't allow ephemeral applications to define new permissions.
11434            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11435                Slog.w(TAG, "Permissions from package " + pkg.packageName
11436                        + " ignored: instant apps cannot define new permissions.");
11437            } else {
11438                mPermissionManager.addAllPermissions(pkg, chatty);
11439            }
11440
11441            N = pkg.instrumentation.size();
11442            r = null;
11443            for (i=0; i<N; i++) {
11444                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11445                a.info.packageName = pkg.applicationInfo.packageName;
11446                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11447                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11448                a.info.splitNames = pkg.splitNames;
11449                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11450                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11451                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11452                a.info.dataDir = pkg.applicationInfo.dataDir;
11453                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11454                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11455                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11456                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11457                mInstrumentation.put(a.getComponentName(), a);
11458                if (chatty) {
11459                    if (r == null) {
11460                        r = new StringBuilder(256);
11461                    } else {
11462                        r.append(' ');
11463                    }
11464                    r.append(a.info.name);
11465                }
11466            }
11467            if (r != null) {
11468                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11469            }
11470
11471            if (pkg.protectedBroadcasts != null) {
11472                N = pkg.protectedBroadcasts.size();
11473                synchronized (mProtectedBroadcasts) {
11474                    for (i = 0; i < N; i++) {
11475                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11476                    }
11477                }
11478            }
11479        }
11480
11481        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11482    }
11483
11484    /**
11485     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11486     * is derived purely on the basis of the contents of {@code scanFile} and
11487     * {@code cpuAbiOverride}.
11488     *
11489     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11490     */
11491    private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride,
11492            boolean extractLibs)
11493                    throws PackageManagerException {
11494        // Give ourselves some initial paths; we'll come back for another
11495        // pass once we've determined ABI below.
11496        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11497
11498        // We would never need to extract libs for forward-locked and external packages,
11499        // since the container service will do it for us. We shouldn't attempt to
11500        // extract libs from system app when it was not updated.
11501        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11502                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11503            extractLibs = false;
11504        }
11505
11506        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11507        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11508
11509        NativeLibraryHelper.Handle handle = null;
11510        try {
11511            handle = NativeLibraryHelper.Handle.create(pkg);
11512            // TODO(multiArch): This can be null for apps that didn't go through the
11513            // usual installation process. We can calculate it again, like we
11514            // do during install time.
11515            //
11516            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11517            // unnecessary.
11518            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11519
11520            // Null out the abis so that they can be recalculated.
11521            pkg.applicationInfo.primaryCpuAbi = null;
11522            pkg.applicationInfo.secondaryCpuAbi = null;
11523            if (isMultiArch(pkg.applicationInfo)) {
11524                // Warn if we've set an abiOverride for multi-lib packages..
11525                // By definition, we need to copy both 32 and 64 bit libraries for
11526                // such packages.
11527                if (pkg.cpuAbiOverride != null
11528                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11529                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11530                }
11531
11532                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11533                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11534                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11535                    if (extractLibs) {
11536                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11537                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11538                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11539                                useIsaSpecificSubdirs);
11540                    } else {
11541                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11542                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11543                    }
11544                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11545                }
11546
11547                // Shared library native code should be in the APK zip aligned
11548                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11549                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11550                            "Shared library native lib extraction not supported");
11551                }
11552
11553                maybeThrowExceptionForMultiArchCopy(
11554                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11555
11556                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11557                    if (extractLibs) {
11558                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11559                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11560                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11561                                useIsaSpecificSubdirs);
11562                    } else {
11563                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11564                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11565                    }
11566                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11567                }
11568
11569                maybeThrowExceptionForMultiArchCopy(
11570                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11571
11572                if (abi64 >= 0) {
11573                    // Shared library native libs should be in the APK zip aligned
11574                    if (extractLibs && pkg.isLibrary()) {
11575                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11576                                "Shared library native lib extraction not supported");
11577                    }
11578                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11579                }
11580
11581                if (abi32 >= 0) {
11582                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11583                    if (abi64 >= 0) {
11584                        if (pkg.use32bitAbi) {
11585                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11586                            pkg.applicationInfo.primaryCpuAbi = abi;
11587                        } else {
11588                            pkg.applicationInfo.secondaryCpuAbi = abi;
11589                        }
11590                    } else {
11591                        pkg.applicationInfo.primaryCpuAbi = abi;
11592                    }
11593                }
11594            } else {
11595                String[] abiList = (cpuAbiOverride != null) ?
11596                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11597
11598                // Enable gross and lame hacks for apps that are built with old
11599                // SDK tools. We must scan their APKs for renderscript bitcode and
11600                // not launch them if it's present. Don't bother checking on devices
11601                // that don't have 64 bit support.
11602                boolean needsRenderScriptOverride = false;
11603                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11604                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11605                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11606                    needsRenderScriptOverride = true;
11607                }
11608
11609                final int copyRet;
11610                if (extractLibs) {
11611                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11612                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11613                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11614                } else {
11615                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11616                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11617                }
11618                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11619
11620                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11621                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11622                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11623                }
11624
11625                if (copyRet >= 0) {
11626                    // Shared libraries that have native libs must be multi-architecture
11627                    if (pkg.isLibrary()) {
11628                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11629                                "Shared library with native libs must be multiarch");
11630                    }
11631                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11632                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11633                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11634                } else if (needsRenderScriptOverride) {
11635                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11636                }
11637            }
11638        } catch (IOException ioe) {
11639            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11640        } finally {
11641            IoUtils.closeQuietly(handle);
11642        }
11643
11644        // Now that we've calculated the ABIs and determined if it's an internal app,
11645        // we will go ahead and populate the nativeLibraryPath.
11646        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11647    }
11648
11649    /**
11650     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11651     * i.e, so that all packages can be run inside a single process if required.
11652     *
11653     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11654     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11655     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11656     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11657     * updating a package that belongs to a shared user.
11658     *
11659     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11660     * adds unnecessary complexity.
11661     */
11662    private static @Nullable List<String> adjustCpuAbisForSharedUserLPw(
11663            Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) {
11664        List<String> changedAbiCodePath = null;
11665        String requiredInstructionSet = null;
11666        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11667            requiredInstructionSet = VMRuntime.getInstructionSet(
11668                     scannedPackage.applicationInfo.primaryCpuAbi);
11669        }
11670
11671        PackageSetting requirer = null;
11672        for (PackageSetting ps : packagesForUser) {
11673            // If packagesForUser contains scannedPackage, we skip it. This will happen
11674            // when scannedPackage is an update of an existing package. Without this check,
11675            // we will never be able to change the ABI of any package belonging to a shared
11676            // user, even if it's compatible with other packages.
11677            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11678                if (ps.primaryCpuAbiString == null) {
11679                    continue;
11680                }
11681
11682                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11683                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11684                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11685                    // this but there's not much we can do.
11686                    String errorMessage = "Instruction set mismatch, "
11687                            + ((requirer == null) ? "[caller]" : requirer)
11688                            + " requires " + requiredInstructionSet + " whereas " + ps
11689                            + " requires " + instructionSet;
11690                    Slog.w(TAG, errorMessage);
11691                }
11692
11693                if (requiredInstructionSet == null) {
11694                    requiredInstructionSet = instructionSet;
11695                    requirer = ps;
11696                }
11697            }
11698        }
11699
11700        if (requiredInstructionSet != null) {
11701            String adjustedAbi;
11702            if (requirer != null) {
11703                // requirer != null implies that either scannedPackage was null or that scannedPackage
11704                // did not require an ABI, in which case we have to adjust scannedPackage to match
11705                // the ABI of the set (which is the same as requirer's ABI)
11706                adjustedAbi = requirer.primaryCpuAbiString;
11707                if (scannedPackage != null) {
11708                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11709                }
11710            } else {
11711                // requirer == null implies that we're updating all ABIs in the set to
11712                // match scannedPackage.
11713                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11714            }
11715
11716            for (PackageSetting ps : packagesForUser) {
11717                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11718                    if (ps.primaryCpuAbiString != null) {
11719                        continue;
11720                    }
11721
11722                    ps.primaryCpuAbiString = adjustedAbi;
11723                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11724                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11725                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11726                        if (DEBUG_ABI_SELECTION) {
11727                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11728                                    + " (requirer="
11729                                    + (requirer != null ? requirer.pkg : "null")
11730                                    + ", scannedPackage="
11731                                    + (scannedPackage != null ? scannedPackage : "null")
11732                                    + ")");
11733                        }
11734                        if (changedAbiCodePath == null) {
11735                            changedAbiCodePath = new ArrayList<>();
11736                        }
11737                        changedAbiCodePath.add(ps.codePathString);
11738                    }
11739                }
11740            }
11741        }
11742        return changedAbiCodePath;
11743    }
11744
11745    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11746        synchronized (mPackages) {
11747            mResolverReplaced = true;
11748            // Set up information for custom user intent resolution activity.
11749            mResolveActivity.applicationInfo = pkg.applicationInfo;
11750            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11751            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11752            mResolveActivity.processName = pkg.applicationInfo.packageName;
11753            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11754            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11755                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11756            mResolveActivity.theme = 0;
11757            mResolveActivity.exported = true;
11758            mResolveActivity.enabled = true;
11759            mResolveInfo.activityInfo = mResolveActivity;
11760            mResolveInfo.priority = 0;
11761            mResolveInfo.preferredOrder = 0;
11762            mResolveInfo.match = 0;
11763            mResolveComponentName = mCustomResolverComponentName;
11764            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11765                    mResolveComponentName);
11766        }
11767    }
11768
11769    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11770        if (installerActivity == null) {
11771            if (DEBUG_EPHEMERAL) {
11772                Slog.d(TAG, "Clear ephemeral installer activity");
11773            }
11774            mInstantAppInstallerActivity = null;
11775            return;
11776        }
11777
11778        if (DEBUG_EPHEMERAL) {
11779            Slog.d(TAG, "Set ephemeral installer activity: "
11780                    + installerActivity.getComponentName());
11781        }
11782        // Set up information for ephemeral installer activity
11783        mInstantAppInstallerActivity = installerActivity;
11784        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11785                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11786        mInstantAppInstallerActivity.exported = true;
11787        mInstantAppInstallerActivity.enabled = true;
11788        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11789        mInstantAppInstallerInfo.priority = 1;
11790        mInstantAppInstallerInfo.preferredOrder = 1;
11791        mInstantAppInstallerInfo.isDefault = true;
11792        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11793                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11794    }
11795
11796    private static String calculateBundledApkRoot(final String codePathString) {
11797        final File codePath = new File(codePathString);
11798        final File codeRoot;
11799        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11800            codeRoot = Environment.getRootDirectory();
11801        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11802            codeRoot = Environment.getOemDirectory();
11803        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11804            codeRoot = Environment.getVendorDirectory();
11805        } else if (FileUtils.contains(Environment.getProductDirectory(), codePath)) {
11806            codeRoot = Environment.getProductDirectory();
11807        } else {
11808            // Unrecognized code path; take its top real segment as the apk root:
11809            // e.g. /something/app/blah.apk => /something
11810            try {
11811                File f = codePath.getCanonicalFile();
11812                File parent = f.getParentFile();    // non-null because codePath is a file
11813                File tmp;
11814                while ((tmp = parent.getParentFile()) != null) {
11815                    f = parent;
11816                    parent = tmp;
11817                }
11818                codeRoot = f;
11819                Slog.w(TAG, "Unrecognized code path "
11820                        + codePath + " - using " + codeRoot);
11821            } catch (IOException e) {
11822                // Can't canonicalize the code path -- shenanigans?
11823                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11824                return Environment.getRootDirectory().getPath();
11825            }
11826        }
11827        return codeRoot.getPath();
11828    }
11829
11830    /**
11831     * Derive and set the location of native libraries for the given package,
11832     * which varies depending on where and how the package was installed.
11833     */
11834    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11835        final ApplicationInfo info = pkg.applicationInfo;
11836        final String codePath = pkg.codePath;
11837        final File codeFile = new File(codePath);
11838        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11839        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11840
11841        info.nativeLibraryRootDir = null;
11842        info.nativeLibraryRootRequiresIsa = false;
11843        info.nativeLibraryDir = null;
11844        info.secondaryNativeLibraryDir = null;
11845
11846        if (isApkFile(codeFile)) {
11847            // Monolithic install
11848            if (bundledApp) {
11849                // If "/system/lib64/apkname" exists, assume that is the per-package
11850                // native library directory to use; otherwise use "/system/lib/apkname".
11851                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11852                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11853                        getPrimaryInstructionSet(info));
11854
11855                // This is a bundled system app so choose the path based on the ABI.
11856                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11857                // is just the default path.
11858                final String apkName = deriveCodePathName(codePath);
11859                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11860                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11861                        apkName).getAbsolutePath();
11862
11863                if (info.secondaryCpuAbi != null) {
11864                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11865                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11866                            secondaryLibDir, apkName).getAbsolutePath();
11867                }
11868            } else if (asecApp) {
11869                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11870                        .getAbsolutePath();
11871            } else {
11872                final String apkName = deriveCodePathName(codePath);
11873                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11874                        .getAbsolutePath();
11875            }
11876
11877            info.nativeLibraryRootRequiresIsa = false;
11878            info.nativeLibraryDir = info.nativeLibraryRootDir;
11879        } else {
11880            // Cluster install
11881            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11882            info.nativeLibraryRootRequiresIsa = true;
11883
11884            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11885                    getPrimaryInstructionSet(info)).getAbsolutePath();
11886
11887            if (info.secondaryCpuAbi != null) {
11888                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11889                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11890            }
11891        }
11892    }
11893
11894    /**
11895     * Calculate the abis and roots for a bundled app. These can uniquely
11896     * be determined from the contents of the system partition, i.e whether
11897     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11898     * of this information, and instead assume that the system was built
11899     * sensibly.
11900     */
11901    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11902                                           PackageSetting pkgSetting) {
11903        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11904
11905        // If "/system/lib64/apkname" exists, assume that is the per-package
11906        // native library directory to use; otherwise use "/system/lib/apkname".
11907        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11908        setBundledAppAbi(pkg, apkRoot, apkName);
11909        // pkgSetting might be null during rescan following uninstall of updates
11910        // to a bundled app, so accommodate that possibility.  The settings in
11911        // that case will be established later from the parsed package.
11912        //
11913        // If the settings aren't null, sync them up with what we've just derived.
11914        // note that apkRoot isn't stored in the package settings.
11915        if (pkgSetting != null) {
11916            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11917            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11918        }
11919    }
11920
11921    /**
11922     * Deduces the ABI of a bundled app and sets the relevant fields on the
11923     * parsed pkg object.
11924     *
11925     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11926     *        under which system libraries are installed.
11927     * @param apkName the name of the installed package.
11928     */
11929    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11930        final File codeFile = new File(pkg.codePath);
11931
11932        final boolean has64BitLibs;
11933        final boolean has32BitLibs;
11934        if (isApkFile(codeFile)) {
11935            // Monolithic install
11936            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11937            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11938        } else {
11939            // Cluster install
11940            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11941            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11942                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11943                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11944                has64BitLibs = (new File(rootDir, isa)).exists();
11945            } else {
11946                has64BitLibs = false;
11947            }
11948            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11949                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11950                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11951                has32BitLibs = (new File(rootDir, isa)).exists();
11952            } else {
11953                has32BitLibs = false;
11954            }
11955        }
11956
11957        if (has64BitLibs && !has32BitLibs) {
11958            // The package has 64 bit libs, but not 32 bit libs. Its primary
11959            // ABI should be 64 bit. We can safely assume here that the bundled
11960            // native libraries correspond to the most preferred ABI in the list.
11961
11962            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11963            pkg.applicationInfo.secondaryCpuAbi = null;
11964        } else if (has32BitLibs && !has64BitLibs) {
11965            // The package has 32 bit libs but not 64 bit libs. Its primary
11966            // ABI should be 32 bit.
11967
11968            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11969            pkg.applicationInfo.secondaryCpuAbi = null;
11970        } else if (has32BitLibs && has64BitLibs) {
11971            // The application has both 64 and 32 bit bundled libraries. We check
11972            // here that the app declares multiArch support, and warn if it doesn't.
11973            //
11974            // We will be lenient here and record both ABIs. The primary will be the
11975            // ABI that's higher on the list, i.e, a device that's configured to prefer
11976            // 64 bit apps will see a 64 bit primary ABI,
11977
11978            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11979                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11980            }
11981
11982            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11983                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11984                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11985            } else {
11986                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11987                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11988            }
11989        } else {
11990            pkg.applicationInfo.primaryCpuAbi = null;
11991            pkg.applicationInfo.secondaryCpuAbi = null;
11992        }
11993    }
11994
11995    private void killApplication(String pkgName, int appId, String reason) {
11996        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11997    }
11998
11999    private void killApplication(String pkgName, int appId, int userId, String reason) {
12000        // Request the ActivityManager to kill the process(only for existing packages)
12001        // so that we do not end up in a confused state while the user is still using the older
12002        // version of the application while the new one gets installed.
12003        final long token = Binder.clearCallingIdentity();
12004        try {
12005            IActivityManager am = ActivityManager.getService();
12006            if (am != null) {
12007                try {
12008                    am.killApplication(pkgName, appId, userId, reason);
12009                } catch (RemoteException e) {
12010                }
12011            }
12012        } finally {
12013            Binder.restoreCallingIdentity(token);
12014        }
12015    }
12016
12017    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12018        // Remove the parent package setting
12019        PackageSetting ps = (PackageSetting) pkg.mExtras;
12020        if (ps != null) {
12021            removePackageLI(ps, chatty);
12022        }
12023        // Remove the child package setting
12024        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12025        for (int i = 0; i < childCount; i++) {
12026            PackageParser.Package childPkg = pkg.childPackages.get(i);
12027            ps = (PackageSetting) childPkg.mExtras;
12028            if (ps != null) {
12029                removePackageLI(ps, chatty);
12030            }
12031        }
12032    }
12033
12034    void removePackageLI(PackageSetting ps, boolean chatty) {
12035        if (DEBUG_INSTALL) {
12036            if (chatty)
12037                Log.d(TAG, "Removing package " + ps.name);
12038        }
12039
12040        // writer
12041        synchronized (mPackages) {
12042            mPackages.remove(ps.name);
12043            final PackageParser.Package pkg = ps.pkg;
12044            if (pkg != null) {
12045                cleanPackageDataStructuresLILPw(pkg, chatty);
12046            }
12047        }
12048    }
12049
12050    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12051        if (DEBUG_INSTALL) {
12052            if (chatty)
12053                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12054        }
12055
12056        // writer
12057        synchronized (mPackages) {
12058            // Remove the parent package
12059            mPackages.remove(pkg.applicationInfo.packageName);
12060            cleanPackageDataStructuresLILPw(pkg, chatty);
12061
12062            // Remove the child packages
12063            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12064            for (int i = 0; i < childCount; i++) {
12065                PackageParser.Package childPkg = pkg.childPackages.get(i);
12066                mPackages.remove(childPkg.applicationInfo.packageName);
12067                cleanPackageDataStructuresLILPw(childPkg, chatty);
12068            }
12069        }
12070    }
12071
12072    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12073        int N = pkg.providers.size();
12074        StringBuilder r = null;
12075        int i;
12076        for (i=0; i<N; i++) {
12077            PackageParser.Provider p = pkg.providers.get(i);
12078            mProviders.removeProvider(p);
12079            if (p.info.authority == null) {
12080
12081                /* There was another ContentProvider with this authority when
12082                 * this app was installed so this authority is null,
12083                 * Ignore it as we don't have to unregister the provider.
12084                 */
12085                continue;
12086            }
12087            String names[] = p.info.authority.split(";");
12088            for (int j = 0; j < names.length; j++) {
12089                if (mProvidersByAuthority.get(names[j]) == p) {
12090                    mProvidersByAuthority.remove(names[j]);
12091                    if (DEBUG_REMOVE) {
12092                        if (chatty)
12093                            Log.d(TAG, "Unregistered content provider: " + names[j]
12094                                    + ", className = " + p.info.name + ", isSyncable = "
12095                                    + p.info.isSyncable);
12096                    }
12097                }
12098            }
12099            if (DEBUG_REMOVE && chatty) {
12100                if (r == null) {
12101                    r = new StringBuilder(256);
12102                } else {
12103                    r.append(' ');
12104                }
12105                r.append(p.info.name);
12106            }
12107        }
12108        if (r != null) {
12109            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12110        }
12111
12112        N = pkg.services.size();
12113        r = null;
12114        for (i=0; i<N; i++) {
12115            PackageParser.Service s = pkg.services.get(i);
12116            mServices.removeService(s);
12117            if (chatty) {
12118                if (r == null) {
12119                    r = new StringBuilder(256);
12120                } else {
12121                    r.append(' ');
12122                }
12123                r.append(s.info.name);
12124            }
12125        }
12126        if (r != null) {
12127            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12128        }
12129
12130        N = pkg.receivers.size();
12131        r = null;
12132        for (i=0; i<N; i++) {
12133            PackageParser.Activity a = pkg.receivers.get(i);
12134            mReceivers.removeActivity(a, "receiver");
12135            if (DEBUG_REMOVE && chatty) {
12136                if (r == null) {
12137                    r = new StringBuilder(256);
12138                } else {
12139                    r.append(' ');
12140                }
12141                r.append(a.info.name);
12142            }
12143        }
12144        if (r != null) {
12145            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12146        }
12147
12148        N = pkg.activities.size();
12149        r = null;
12150        for (i=0; i<N; i++) {
12151            PackageParser.Activity a = pkg.activities.get(i);
12152            mActivities.removeActivity(a, "activity");
12153            if (DEBUG_REMOVE && chatty) {
12154                if (r == null) {
12155                    r = new StringBuilder(256);
12156                } else {
12157                    r.append(' ');
12158                }
12159                r.append(a.info.name);
12160            }
12161        }
12162        if (r != null) {
12163            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12164        }
12165
12166        mPermissionManager.removeAllPermissions(pkg, chatty);
12167
12168        N = pkg.instrumentation.size();
12169        r = null;
12170        for (i=0; i<N; i++) {
12171            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12172            mInstrumentation.remove(a.getComponentName());
12173            if (DEBUG_REMOVE && chatty) {
12174                if (r == null) {
12175                    r = new StringBuilder(256);
12176                } else {
12177                    r.append(' ');
12178                }
12179                r.append(a.info.name);
12180            }
12181        }
12182        if (r != null) {
12183            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12184        }
12185
12186        r = null;
12187        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12188            // Only system apps can hold shared libraries.
12189            if (pkg.libraryNames != null) {
12190                for (i = 0; i < pkg.libraryNames.size(); i++) {
12191                    String name = pkg.libraryNames.get(i);
12192                    if (removeSharedLibraryLPw(name, 0)) {
12193                        if (DEBUG_REMOVE && chatty) {
12194                            if (r == null) {
12195                                r = new StringBuilder(256);
12196                            } else {
12197                                r.append(' ');
12198                            }
12199                            r.append(name);
12200                        }
12201                    }
12202                }
12203            }
12204        }
12205
12206        r = null;
12207
12208        // Any package can hold static shared libraries.
12209        if (pkg.staticSharedLibName != null) {
12210            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12211                if (DEBUG_REMOVE && chatty) {
12212                    if (r == null) {
12213                        r = new StringBuilder(256);
12214                    } else {
12215                        r.append(' ');
12216                    }
12217                    r.append(pkg.staticSharedLibName);
12218                }
12219            }
12220        }
12221
12222        if (r != null) {
12223            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12224        }
12225    }
12226
12227
12228    final class ActivityIntentResolver
12229            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12230        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12231                boolean defaultOnly, int userId) {
12232            if (!sUserManager.exists(userId)) return null;
12233            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12234            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12235        }
12236
12237        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12238                int userId) {
12239            if (!sUserManager.exists(userId)) return null;
12240            mFlags = flags;
12241            return super.queryIntent(intent, resolvedType,
12242                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12243                    userId);
12244        }
12245
12246        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12247                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12248            if (!sUserManager.exists(userId)) return null;
12249            if (packageActivities == null) {
12250                return null;
12251            }
12252            mFlags = flags;
12253            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12254            final int N = packageActivities.size();
12255            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12256                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12257
12258            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12259            for (int i = 0; i < N; ++i) {
12260                intentFilters = packageActivities.get(i).intents;
12261                if (intentFilters != null && intentFilters.size() > 0) {
12262                    PackageParser.ActivityIntentInfo[] array =
12263                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12264                    intentFilters.toArray(array);
12265                    listCut.add(array);
12266                }
12267            }
12268            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12269        }
12270
12271        /**
12272         * Finds a privileged activity that matches the specified activity names.
12273         */
12274        private PackageParser.Activity findMatchingActivity(
12275                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12276            for (PackageParser.Activity sysActivity : activityList) {
12277                if (sysActivity.info.name.equals(activityInfo.name)) {
12278                    return sysActivity;
12279                }
12280                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12281                    return sysActivity;
12282                }
12283                if (sysActivity.info.targetActivity != null) {
12284                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12285                        return sysActivity;
12286                    }
12287                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12288                        return sysActivity;
12289                    }
12290                }
12291            }
12292            return null;
12293        }
12294
12295        public class IterGenerator<E> {
12296            public Iterator<E> generate(ActivityIntentInfo info) {
12297                return null;
12298            }
12299        }
12300
12301        public class ActionIterGenerator extends IterGenerator<String> {
12302            @Override
12303            public Iterator<String> generate(ActivityIntentInfo info) {
12304                return info.actionsIterator();
12305            }
12306        }
12307
12308        public class CategoriesIterGenerator extends IterGenerator<String> {
12309            @Override
12310            public Iterator<String> generate(ActivityIntentInfo info) {
12311                return info.categoriesIterator();
12312            }
12313        }
12314
12315        public class SchemesIterGenerator extends IterGenerator<String> {
12316            @Override
12317            public Iterator<String> generate(ActivityIntentInfo info) {
12318                return info.schemesIterator();
12319            }
12320        }
12321
12322        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12323            @Override
12324            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12325                return info.authoritiesIterator();
12326            }
12327        }
12328
12329        /**
12330         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12331         * MODIFIED. Do not pass in a list that should not be changed.
12332         */
12333        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12334                IterGenerator<T> generator, Iterator<T> searchIterator) {
12335            // loop through the set of actions; every one must be found in the intent filter
12336            while (searchIterator.hasNext()) {
12337                // we must have at least one filter in the list to consider a match
12338                if (intentList.size() == 0) {
12339                    break;
12340                }
12341
12342                final T searchAction = searchIterator.next();
12343
12344                // loop through the set of intent filters
12345                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12346                while (intentIter.hasNext()) {
12347                    final ActivityIntentInfo intentInfo = intentIter.next();
12348                    boolean selectionFound = false;
12349
12350                    // loop through the intent filter's selection criteria; at least one
12351                    // of them must match the searched criteria
12352                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12353                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12354                        final T intentSelection = intentSelectionIter.next();
12355                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12356                            selectionFound = true;
12357                            break;
12358                        }
12359                    }
12360
12361                    // the selection criteria wasn't found in this filter's set; this filter
12362                    // is not a potential match
12363                    if (!selectionFound) {
12364                        intentIter.remove();
12365                    }
12366                }
12367            }
12368        }
12369
12370        private boolean isProtectedAction(ActivityIntentInfo filter) {
12371            final Iterator<String> actionsIter = filter.actionsIterator();
12372            while (actionsIter != null && actionsIter.hasNext()) {
12373                final String filterAction = actionsIter.next();
12374                if (PROTECTED_ACTIONS.contains(filterAction)) {
12375                    return true;
12376                }
12377            }
12378            return false;
12379        }
12380
12381        /**
12382         * Adjusts the priority of the given intent filter according to policy.
12383         * <p>
12384         * <ul>
12385         * <li>The priority for non privileged applications is capped to '0'</li>
12386         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12387         * <li>The priority for unbundled updates to privileged applications is capped to the
12388         *      priority defined on the system partition</li>
12389         * </ul>
12390         * <p>
12391         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12392         * allowed to obtain any priority on any action.
12393         */
12394        private void adjustPriority(
12395                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12396            // nothing to do; priority is fine as-is
12397            if (intent.getPriority() <= 0) {
12398                return;
12399            }
12400
12401            final ActivityInfo activityInfo = intent.activity.info;
12402            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12403
12404            final boolean privilegedApp =
12405                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12406            if (!privilegedApp) {
12407                // non-privileged applications can never define a priority >0
12408                if (DEBUG_FILTERS) {
12409                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12410                            + " package: " + applicationInfo.packageName
12411                            + " activity: " + intent.activity.className
12412                            + " origPrio: " + intent.getPriority());
12413                }
12414                intent.setPriority(0);
12415                return;
12416            }
12417
12418            if (systemActivities == null) {
12419                // the system package is not disabled; we're parsing the system partition
12420                if (isProtectedAction(intent)) {
12421                    if (mDeferProtectedFilters) {
12422                        // We can't deal with these just yet. No component should ever obtain a
12423                        // >0 priority for a protected actions, with ONE exception -- the setup
12424                        // wizard. The setup wizard, however, cannot be known until we're able to
12425                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12426                        // until all intent filters have been processed. Chicken, meet egg.
12427                        // Let the filter temporarily have a high priority and rectify the
12428                        // priorities after all system packages have been scanned.
12429                        mProtectedFilters.add(intent);
12430                        if (DEBUG_FILTERS) {
12431                            Slog.i(TAG, "Protected action; save for later;"
12432                                    + " package: " + applicationInfo.packageName
12433                                    + " activity: " + intent.activity.className
12434                                    + " origPrio: " + intent.getPriority());
12435                        }
12436                        return;
12437                    } else {
12438                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12439                            Slog.i(TAG, "No setup wizard;"
12440                                + " All protected intents capped to priority 0");
12441                        }
12442                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12443                            if (DEBUG_FILTERS) {
12444                                Slog.i(TAG, "Found setup wizard;"
12445                                    + " allow priority " + intent.getPriority() + ";"
12446                                    + " package: " + intent.activity.info.packageName
12447                                    + " activity: " + intent.activity.className
12448                                    + " priority: " + intent.getPriority());
12449                            }
12450                            // setup wizard gets whatever it wants
12451                            return;
12452                        }
12453                        if (DEBUG_FILTERS) {
12454                            Slog.i(TAG, "Protected action; cap priority to 0;"
12455                                    + " package: " + intent.activity.info.packageName
12456                                    + " activity: " + intent.activity.className
12457                                    + " origPrio: " + intent.getPriority());
12458                        }
12459                        intent.setPriority(0);
12460                        return;
12461                    }
12462                }
12463                // privileged apps on the system image get whatever priority they request
12464                return;
12465            }
12466
12467            // privileged app unbundled update ... try to find the same activity
12468            final PackageParser.Activity foundActivity =
12469                    findMatchingActivity(systemActivities, activityInfo);
12470            if (foundActivity == null) {
12471                // this is a new activity; it cannot obtain >0 priority
12472                if (DEBUG_FILTERS) {
12473                    Slog.i(TAG, "New activity; cap priority to 0;"
12474                            + " package: " + applicationInfo.packageName
12475                            + " activity: " + intent.activity.className
12476                            + " origPrio: " + intent.getPriority());
12477                }
12478                intent.setPriority(0);
12479                return;
12480            }
12481
12482            // found activity, now check for filter equivalence
12483
12484            // a shallow copy is enough; we modify the list, not its contents
12485            final List<ActivityIntentInfo> intentListCopy =
12486                    new ArrayList<>(foundActivity.intents);
12487            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12488
12489            // find matching action subsets
12490            final Iterator<String> actionsIterator = intent.actionsIterator();
12491            if (actionsIterator != null) {
12492                getIntentListSubset(
12493                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12494                if (intentListCopy.size() == 0) {
12495                    // no more intents to match; we're not equivalent
12496                    if (DEBUG_FILTERS) {
12497                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12498                                + " package: " + applicationInfo.packageName
12499                                + " activity: " + intent.activity.className
12500                                + " origPrio: " + intent.getPriority());
12501                    }
12502                    intent.setPriority(0);
12503                    return;
12504                }
12505            }
12506
12507            // find matching category subsets
12508            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12509            if (categoriesIterator != null) {
12510                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12511                        categoriesIterator);
12512                if (intentListCopy.size() == 0) {
12513                    // no more intents to match; we're not equivalent
12514                    if (DEBUG_FILTERS) {
12515                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12516                                + " package: " + applicationInfo.packageName
12517                                + " activity: " + intent.activity.className
12518                                + " origPrio: " + intent.getPriority());
12519                    }
12520                    intent.setPriority(0);
12521                    return;
12522                }
12523            }
12524
12525            // find matching schemes subsets
12526            final Iterator<String> schemesIterator = intent.schemesIterator();
12527            if (schemesIterator != null) {
12528                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12529                        schemesIterator);
12530                if (intentListCopy.size() == 0) {
12531                    // no more intents to match; we're not equivalent
12532                    if (DEBUG_FILTERS) {
12533                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12534                                + " package: " + applicationInfo.packageName
12535                                + " activity: " + intent.activity.className
12536                                + " origPrio: " + intent.getPriority());
12537                    }
12538                    intent.setPriority(0);
12539                    return;
12540                }
12541            }
12542
12543            // find matching authorities subsets
12544            final Iterator<IntentFilter.AuthorityEntry>
12545                    authoritiesIterator = intent.authoritiesIterator();
12546            if (authoritiesIterator != null) {
12547                getIntentListSubset(intentListCopy,
12548                        new AuthoritiesIterGenerator(),
12549                        authoritiesIterator);
12550                if (intentListCopy.size() == 0) {
12551                    // no more intents to match; we're not equivalent
12552                    if (DEBUG_FILTERS) {
12553                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12554                                + " package: " + applicationInfo.packageName
12555                                + " activity: " + intent.activity.className
12556                                + " origPrio: " + intent.getPriority());
12557                    }
12558                    intent.setPriority(0);
12559                    return;
12560                }
12561            }
12562
12563            // we found matching filter(s); app gets the max priority of all intents
12564            int cappedPriority = 0;
12565            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12566                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12567            }
12568            if (intent.getPriority() > cappedPriority) {
12569                if (DEBUG_FILTERS) {
12570                    Slog.i(TAG, "Found matching filter(s);"
12571                            + " cap priority to " + cappedPriority + ";"
12572                            + " package: " + applicationInfo.packageName
12573                            + " activity: " + intent.activity.className
12574                            + " origPrio: " + intent.getPriority());
12575                }
12576                intent.setPriority(cappedPriority);
12577                return;
12578            }
12579            // all this for nothing; the requested priority was <= what was on the system
12580        }
12581
12582        public final void addActivity(PackageParser.Activity a, String type) {
12583            mActivities.put(a.getComponentName(), a);
12584            if (DEBUG_SHOW_INFO)
12585                Log.v(
12586                TAG, "  " + type + " " +
12587                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12588            if (DEBUG_SHOW_INFO)
12589                Log.v(TAG, "    Class=" + a.info.name);
12590            final int NI = a.intents.size();
12591            for (int j=0; j<NI; j++) {
12592                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12593                if ("activity".equals(type)) {
12594                    final PackageSetting ps =
12595                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12596                    final List<PackageParser.Activity> systemActivities =
12597                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12598                    adjustPriority(systemActivities, intent);
12599                }
12600                if (DEBUG_SHOW_INFO) {
12601                    Log.v(TAG, "    IntentFilter:");
12602                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12603                }
12604                if (!intent.debugCheck()) {
12605                    Log.w(TAG, "==> For Activity " + a.info.name);
12606                }
12607                addFilter(intent);
12608            }
12609        }
12610
12611        public final void removeActivity(PackageParser.Activity a, String type) {
12612            mActivities.remove(a.getComponentName());
12613            if (DEBUG_SHOW_INFO) {
12614                Log.v(TAG, "  " + type + " "
12615                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12616                                : a.info.name) + ":");
12617                Log.v(TAG, "    Class=" + a.info.name);
12618            }
12619            final int NI = a.intents.size();
12620            for (int j=0; j<NI; j++) {
12621                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12622                if (DEBUG_SHOW_INFO) {
12623                    Log.v(TAG, "    IntentFilter:");
12624                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12625                }
12626                removeFilter(intent);
12627            }
12628        }
12629
12630        @Override
12631        protected boolean allowFilterResult(
12632                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12633            ActivityInfo filterAi = filter.activity.info;
12634            for (int i=dest.size()-1; i>=0; i--) {
12635                ActivityInfo destAi = dest.get(i).activityInfo;
12636                if (destAi.name == filterAi.name
12637                        && destAi.packageName == filterAi.packageName) {
12638                    return false;
12639                }
12640            }
12641            return true;
12642        }
12643
12644        @Override
12645        protected ActivityIntentInfo[] newArray(int size) {
12646            return new ActivityIntentInfo[size];
12647        }
12648
12649        @Override
12650        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12651            if (!sUserManager.exists(userId)) return true;
12652            PackageParser.Package p = filter.activity.owner;
12653            if (p != null) {
12654                PackageSetting ps = (PackageSetting)p.mExtras;
12655                if (ps != null) {
12656                    // System apps are never considered stopped for purposes of
12657                    // filtering, because there may be no way for the user to
12658                    // actually re-launch them.
12659                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12660                            && ps.getStopped(userId);
12661                }
12662            }
12663            return false;
12664        }
12665
12666        @Override
12667        protected boolean isPackageForFilter(String packageName,
12668                PackageParser.ActivityIntentInfo info) {
12669            return packageName.equals(info.activity.owner.packageName);
12670        }
12671
12672        @Override
12673        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12674                int match, int userId) {
12675            if (!sUserManager.exists(userId)) return null;
12676            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12677                return null;
12678            }
12679            final PackageParser.Activity activity = info.activity;
12680            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12681            if (ps == null) {
12682                return null;
12683            }
12684            final PackageUserState userState = ps.readUserState(userId);
12685            ActivityInfo ai =
12686                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
12687            if (ai == null) {
12688                return null;
12689            }
12690            final boolean matchExplicitlyVisibleOnly =
12691                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12692            final boolean matchVisibleToInstantApp =
12693                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12694            final boolean componentVisible =
12695                    matchVisibleToInstantApp
12696                    && info.isVisibleToInstantApp()
12697                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12698            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12699            // throw out filters that aren't visible to ephemeral apps
12700            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12701                return null;
12702            }
12703            // throw out instant app filters if we're not explicitly requesting them
12704            if (!matchInstantApp && userState.instantApp) {
12705                return null;
12706            }
12707            // throw out instant app filters if updates are available; will trigger
12708            // instant app resolution
12709            if (userState.instantApp && ps.isUpdateAvailable()) {
12710                return null;
12711            }
12712            final ResolveInfo res = new ResolveInfo();
12713            res.activityInfo = ai;
12714            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12715                res.filter = info;
12716            }
12717            if (info != null) {
12718                res.handleAllWebDataURI = info.handleAllWebDataURI();
12719            }
12720            res.priority = info.getPriority();
12721            res.preferredOrder = activity.owner.mPreferredOrder;
12722            //System.out.println("Result: " + res.activityInfo.className +
12723            //                   " = " + res.priority);
12724            res.match = match;
12725            res.isDefault = info.hasDefault;
12726            res.labelRes = info.labelRes;
12727            res.nonLocalizedLabel = info.nonLocalizedLabel;
12728            if (userNeedsBadging(userId)) {
12729                res.noResourceId = true;
12730            } else {
12731                res.icon = info.icon;
12732            }
12733            res.iconResourceId = info.icon;
12734            res.system = res.activityInfo.applicationInfo.isSystemApp();
12735            res.isInstantAppAvailable = userState.instantApp;
12736            return res;
12737        }
12738
12739        @Override
12740        protected void sortResults(List<ResolveInfo> results) {
12741            Collections.sort(results, mResolvePrioritySorter);
12742        }
12743
12744        @Override
12745        protected void dumpFilter(PrintWriter out, String prefix,
12746                PackageParser.ActivityIntentInfo filter) {
12747            out.print(prefix); out.print(
12748                    Integer.toHexString(System.identityHashCode(filter.activity)));
12749                    out.print(' ');
12750                    filter.activity.printComponentShortName(out);
12751                    out.print(" filter ");
12752                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12753        }
12754
12755        @Override
12756        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12757            return filter.activity;
12758        }
12759
12760        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12761            PackageParser.Activity activity = (PackageParser.Activity)label;
12762            out.print(prefix); out.print(
12763                    Integer.toHexString(System.identityHashCode(activity)));
12764                    out.print(' ');
12765                    activity.printComponentShortName(out);
12766            if (count > 1) {
12767                out.print(" ("); out.print(count); out.print(" filters)");
12768            }
12769            out.println();
12770        }
12771
12772        // Keys are String (activity class name), values are Activity.
12773        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12774                = new ArrayMap<ComponentName, PackageParser.Activity>();
12775        private int mFlags;
12776    }
12777
12778    private final class ServiceIntentResolver
12779            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12780        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12781                boolean defaultOnly, int userId) {
12782            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12783            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12784        }
12785
12786        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12787                int userId) {
12788            if (!sUserManager.exists(userId)) return null;
12789            mFlags = flags;
12790            return super.queryIntent(intent, resolvedType,
12791                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12792                    userId);
12793        }
12794
12795        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12796                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12797            if (!sUserManager.exists(userId)) return null;
12798            if (packageServices == null) {
12799                return null;
12800            }
12801            mFlags = flags;
12802            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12803            final int N = packageServices.size();
12804            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12805                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12806
12807            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12808            for (int i = 0; i < N; ++i) {
12809                intentFilters = packageServices.get(i).intents;
12810                if (intentFilters != null && intentFilters.size() > 0) {
12811                    PackageParser.ServiceIntentInfo[] array =
12812                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12813                    intentFilters.toArray(array);
12814                    listCut.add(array);
12815                }
12816            }
12817            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12818        }
12819
12820        public final void addService(PackageParser.Service s) {
12821            mServices.put(s.getComponentName(), s);
12822            if (DEBUG_SHOW_INFO) {
12823                Log.v(TAG, "  "
12824                        + (s.info.nonLocalizedLabel != null
12825                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12826                Log.v(TAG, "    Class=" + s.info.name);
12827            }
12828            final int NI = s.intents.size();
12829            int j;
12830            for (j=0; j<NI; j++) {
12831                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12832                if (DEBUG_SHOW_INFO) {
12833                    Log.v(TAG, "    IntentFilter:");
12834                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12835                }
12836                if (!intent.debugCheck()) {
12837                    Log.w(TAG, "==> For Service " + s.info.name);
12838                }
12839                addFilter(intent);
12840            }
12841        }
12842
12843        public final void removeService(PackageParser.Service s) {
12844            mServices.remove(s.getComponentName());
12845            if (DEBUG_SHOW_INFO) {
12846                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12847                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12848                Log.v(TAG, "    Class=" + s.info.name);
12849            }
12850            final int NI = s.intents.size();
12851            int j;
12852            for (j=0; j<NI; j++) {
12853                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12854                if (DEBUG_SHOW_INFO) {
12855                    Log.v(TAG, "    IntentFilter:");
12856                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12857                }
12858                removeFilter(intent);
12859            }
12860        }
12861
12862        @Override
12863        protected boolean allowFilterResult(
12864                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12865            ServiceInfo filterSi = filter.service.info;
12866            for (int i=dest.size()-1; i>=0; i--) {
12867                ServiceInfo destAi = dest.get(i).serviceInfo;
12868                if (destAi.name == filterSi.name
12869                        && destAi.packageName == filterSi.packageName) {
12870                    return false;
12871                }
12872            }
12873            return true;
12874        }
12875
12876        @Override
12877        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12878            return new PackageParser.ServiceIntentInfo[size];
12879        }
12880
12881        @Override
12882        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12883            if (!sUserManager.exists(userId)) return true;
12884            PackageParser.Package p = filter.service.owner;
12885            if (p != null) {
12886                PackageSetting ps = (PackageSetting)p.mExtras;
12887                if (ps != null) {
12888                    // System apps are never considered stopped for purposes of
12889                    // filtering, because there may be no way for the user to
12890                    // actually re-launch them.
12891                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12892                            && ps.getStopped(userId);
12893                }
12894            }
12895            return false;
12896        }
12897
12898        @Override
12899        protected boolean isPackageForFilter(String packageName,
12900                PackageParser.ServiceIntentInfo info) {
12901            return packageName.equals(info.service.owner.packageName);
12902        }
12903
12904        @Override
12905        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12906                int match, int userId) {
12907            if (!sUserManager.exists(userId)) return null;
12908            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12909            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12910                return null;
12911            }
12912            final PackageParser.Service service = info.service;
12913            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12914            if (ps == null) {
12915                return null;
12916            }
12917            final PackageUserState userState = ps.readUserState(userId);
12918            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12919                    userState, userId);
12920            if (si == null) {
12921                return null;
12922            }
12923            final boolean matchVisibleToInstantApp =
12924                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12925            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12926            // throw out filters that aren't visible to ephemeral apps
12927            if (matchVisibleToInstantApp
12928                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12929                return null;
12930            }
12931            // throw out ephemeral filters if we're not explicitly requesting them
12932            if (!isInstantApp && userState.instantApp) {
12933                return null;
12934            }
12935            // throw out instant app filters if updates are available; will trigger
12936            // instant app resolution
12937            if (userState.instantApp && ps.isUpdateAvailable()) {
12938                return null;
12939            }
12940            final ResolveInfo res = new ResolveInfo();
12941            res.serviceInfo = si;
12942            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12943                res.filter = filter;
12944            }
12945            res.priority = info.getPriority();
12946            res.preferredOrder = service.owner.mPreferredOrder;
12947            res.match = match;
12948            res.isDefault = info.hasDefault;
12949            res.labelRes = info.labelRes;
12950            res.nonLocalizedLabel = info.nonLocalizedLabel;
12951            res.icon = info.icon;
12952            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12953            return res;
12954        }
12955
12956        @Override
12957        protected void sortResults(List<ResolveInfo> results) {
12958            Collections.sort(results, mResolvePrioritySorter);
12959        }
12960
12961        @Override
12962        protected void dumpFilter(PrintWriter out, String prefix,
12963                PackageParser.ServiceIntentInfo filter) {
12964            out.print(prefix); out.print(
12965                    Integer.toHexString(System.identityHashCode(filter.service)));
12966                    out.print(' ');
12967                    filter.service.printComponentShortName(out);
12968                    out.print(" filter ");
12969                    out.print(Integer.toHexString(System.identityHashCode(filter)));
12970                    if (filter.service.info.permission != null) {
12971                        out.print(" permission "); out.println(filter.service.info.permission);
12972                    } else {
12973                        out.println();
12974                    }
12975        }
12976
12977        @Override
12978        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12979            return filter.service;
12980        }
12981
12982        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12983            PackageParser.Service service = (PackageParser.Service)label;
12984            out.print(prefix); out.print(
12985                    Integer.toHexString(System.identityHashCode(service)));
12986                    out.print(' ');
12987                    service.printComponentShortName(out);
12988            if (count > 1) {
12989                out.print(" ("); out.print(count); out.print(" filters)");
12990            }
12991            out.println();
12992        }
12993
12994//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12995//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12996//            final List<ResolveInfo> retList = Lists.newArrayList();
12997//            while (i.hasNext()) {
12998//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12999//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13000//                    retList.add(resolveInfo);
13001//                }
13002//            }
13003//            return retList;
13004//        }
13005
13006        // Keys are String (activity class name), values are Activity.
13007        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13008                = new ArrayMap<ComponentName, PackageParser.Service>();
13009        private int mFlags;
13010    }
13011
13012    private final class ProviderIntentResolver
13013            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13014        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13015                boolean defaultOnly, int userId) {
13016            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13017            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13018        }
13019
13020        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13021                int userId) {
13022            if (!sUserManager.exists(userId))
13023                return null;
13024            mFlags = flags;
13025            return super.queryIntent(intent, resolvedType,
13026                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13027                    userId);
13028        }
13029
13030        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13031                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13032            if (!sUserManager.exists(userId))
13033                return null;
13034            if (packageProviders == null) {
13035                return null;
13036            }
13037            mFlags = flags;
13038            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13039            final int N = packageProviders.size();
13040            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13041                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13042
13043            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13044            for (int i = 0; i < N; ++i) {
13045                intentFilters = packageProviders.get(i).intents;
13046                if (intentFilters != null && intentFilters.size() > 0) {
13047                    PackageParser.ProviderIntentInfo[] array =
13048                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13049                    intentFilters.toArray(array);
13050                    listCut.add(array);
13051                }
13052            }
13053            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13054        }
13055
13056        public final void addProvider(PackageParser.Provider p) {
13057            if (mProviders.containsKey(p.getComponentName())) {
13058                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13059                return;
13060            }
13061
13062            mProviders.put(p.getComponentName(), p);
13063            if (DEBUG_SHOW_INFO) {
13064                Log.v(TAG, "  "
13065                        + (p.info.nonLocalizedLabel != null
13066                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13067                Log.v(TAG, "    Class=" + p.info.name);
13068            }
13069            final int NI = p.intents.size();
13070            int j;
13071            for (j = 0; j < NI; j++) {
13072                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13073                if (DEBUG_SHOW_INFO) {
13074                    Log.v(TAG, "    IntentFilter:");
13075                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13076                }
13077                if (!intent.debugCheck()) {
13078                    Log.w(TAG, "==> For Provider " + p.info.name);
13079                }
13080                addFilter(intent);
13081            }
13082        }
13083
13084        public final void removeProvider(PackageParser.Provider p) {
13085            mProviders.remove(p.getComponentName());
13086            if (DEBUG_SHOW_INFO) {
13087                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13088                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13089                Log.v(TAG, "    Class=" + p.info.name);
13090            }
13091            final int NI = p.intents.size();
13092            int j;
13093            for (j = 0; j < NI; j++) {
13094                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13095                if (DEBUG_SHOW_INFO) {
13096                    Log.v(TAG, "    IntentFilter:");
13097                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13098                }
13099                removeFilter(intent);
13100            }
13101        }
13102
13103        @Override
13104        protected boolean allowFilterResult(
13105                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13106            ProviderInfo filterPi = filter.provider.info;
13107            for (int i = dest.size() - 1; i >= 0; i--) {
13108                ProviderInfo destPi = dest.get(i).providerInfo;
13109                if (destPi.name == filterPi.name
13110                        && destPi.packageName == filterPi.packageName) {
13111                    return false;
13112                }
13113            }
13114            return true;
13115        }
13116
13117        @Override
13118        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13119            return new PackageParser.ProviderIntentInfo[size];
13120        }
13121
13122        @Override
13123        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13124            if (!sUserManager.exists(userId))
13125                return true;
13126            PackageParser.Package p = filter.provider.owner;
13127            if (p != null) {
13128                PackageSetting ps = (PackageSetting) p.mExtras;
13129                if (ps != null) {
13130                    // System apps are never considered stopped for purposes of
13131                    // filtering, because there may be no way for the user to
13132                    // actually re-launch them.
13133                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13134                            && ps.getStopped(userId);
13135                }
13136            }
13137            return false;
13138        }
13139
13140        @Override
13141        protected boolean isPackageForFilter(String packageName,
13142                PackageParser.ProviderIntentInfo info) {
13143            return packageName.equals(info.provider.owner.packageName);
13144        }
13145
13146        @Override
13147        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13148                int match, int userId) {
13149            if (!sUserManager.exists(userId))
13150                return null;
13151            final PackageParser.ProviderIntentInfo info = filter;
13152            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13153                return null;
13154            }
13155            final PackageParser.Provider provider = info.provider;
13156            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13157            if (ps == null) {
13158                return null;
13159            }
13160            final PackageUserState userState = ps.readUserState(userId);
13161            final boolean matchVisibleToInstantApp =
13162                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13163            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13164            // throw out filters that aren't visible to instant applications
13165            if (matchVisibleToInstantApp
13166                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13167                return null;
13168            }
13169            // throw out instant application filters if we're not explicitly requesting them
13170            if (!isInstantApp && userState.instantApp) {
13171                return null;
13172            }
13173            // throw out instant application filters if updates are available; will trigger
13174            // instant application resolution
13175            if (userState.instantApp && ps.isUpdateAvailable()) {
13176                return null;
13177            }
13178            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13179                    userState, userId);
13180            if (pi == null) {
13181                return null;
13182            }
13183            final ResolveInfo res = new ResolveInfo();
13184            res.providerInfo = pi;
13185            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13186                res.filter = filter;
13187            }
13188            res.priority = info.getPriority();
13189            res.preferredOrder = provider.owner.mPreferredOrder;
13190            res.match = match;
13191            res.isDefault = info.hasDefault;
13192            res.labelRes = info.labelRes;
13193            res.nonLocalizedLabel = info.nonLocalizedLabel;
13194            res.icon = info.icon;
13195            res.system = res.providerInfo.applicationInfo.isSystemApp();
13196            return res;
13197        }
13198
13199        @Override
13200        protected void sortResults(List<ResolveInfo> results) {
13201            Collections.sort(results, mResolvePrioritySorter);
13202        }
13203
13204        @Override
13205        protected void dumpFilter(PrintWriter out, String prefix,
13206                PackageParser.ProviderIntentInfo filter) {
13207            out.print(prefix);
13208            out.print(
13209                    Integer.toHexString(System.identityHashCode(filter.provider)));
13210            out.print(' ');
13211            filter.provider.printComponentShortName(out);
13212            out.print(" filter ");
13213            out.println(Integer.toHexString(System.identityHashCode(filter)));
13214        }
13215
13216        @Override
13217        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13218            return filter.provider;
13219        }
13220
13221        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13222            PackageParser.Provider provider = (PackageParser.Provider)label;
13223            out.print(prefix); out.print(
13224                    Integer.toHexString(System.identityHashCode(provider)));
13225                    out.print(' ');
13226                    provider.printComponentShortName(out);
13227            if (count > 1) {
13228                out.print(" ("); out.print(count); out.print(" filters)");
13229            }
13230            out.println();
13231        }
13232
13233        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13234                = new ArrayMap<ComponentName, PackageParser.Provider>();
13235        private int mFlags;
13236    }
13237
13238    static final class EphemeralIntentResolver
13239            extends IntentResolver<AuxiliaryResolveInfo.AuxiliaryFilter,
13240            AuxiliaryResolveInfo.AuxiliaryFilter> {
13241        /**
13242         * The result that has the highest defined order. Ordering applies on a
13243         * per-package basis. Mapping is from package name to Pair of order and
13244         * EphemeralResolveInfo.
13245         * <p>
13246         * NOTE: This is implemented as a field variable for convenience and efficiency.
13247         * By having a field variable, we're able to track filter ordering as soon as
13248         * a non-zero order is defined. Otherwise, multiple loops across the result set
13249         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13250         * this needs to be contained entirely within {@link #filterResults}.
13251         */
13252        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13253
13254        @Override
13255        protected AuxiliaryResolveInfo.AuxiliaryFilter[] newArray(int size) {
13256            return new AuxiliaryResolveInfo.AuxiliaryFilter[size];
13257        }
13258
13259        @Override
13260        protected boolean isPackageForFilter(String packageName,
13261                AuxiliaryResolveInfo.AuxiliaryFilter responseObj) {
13262            return true;
13263        }
13264
13265        @Override
13266        protected AuxiliaryResolveInfo.AuxiliaryFilter newResult(
13267                AuxiliaryResolveInfo.AuxiliaryFilter responseObj, int match, int userId) {
13268            if (!sUserManager.exists(userId)) {
13269                return null;
13270            }
13271            final String packageName = responseObj.resolveInfo.getPackageName();
13272            final Integer order = responseObj.getOrder();
13273            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13274                    mOrderResult.get(packageName);
13275            // ordering is enabled and this item's order isn't high enough
13276            if (lastOrderResult != null && lastOrderResult.first >= order) {
13277                return null;
13278            }
13279            final InstantAppResolveInfo res = responseObj.resolveInfo;
13280            if (order > 0) {
13281                // non-zero order, enable ordering
13282                mOrderResult.put(packageName, new Pair<>(order, res));
13283            }
13284            return responseObj;
13285        }
13286
13287        @Override
13288        protected void filterResults(List<AuxiliaryResolveInfo.AuxiliaryFilter> results) {
13289            // only do work if ordering is enabled [most of the time it won't be]
13290            if (mOrderResult.size() == 0) {
13291                return;
13292            }
13293            int resultSize = results.size();
13294            for (int i = 0; i < resultSize; i++) {
13295                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13296                final String packageName = info.getPackageName();
13297                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13298                if (savedInfo == null) {
13299                    // package doesn't having ordering
13300                    continue;
13301                }
13302                if (savedInfo.second == info) {
13303                    // circled back to the highest ordered item; remove from order list
13304                    mOrderResult.remove(packageName);
13305                    if (mOrderResult.size() == 0) {
13306                        // no more ordered items
13307                        break;
13308                    }
13309                    continue;
13310                }
13311                // item has a worse order, remove it from the result list
13312                results.remove(i);
13313                resultSize--;
13314                i--;
13315            }
13316        }
13317    }
13318
13319    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13320            new Comparator<ResolveInfo>() {
13321        public int compare(ResolveInfo r1, ResolveInfo r2) {
13322            int v1 = r1.priority;
13323            int v2 = r2.priority;
13324            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13325            if (v1 != v2) {
13326                return (v1 > v2) ? -1 : 1;
13327            }
13328            v1 = r1.preferredOrder;
13329            v2 = r2.preferredOrder;
13330            if (v1 != v2) {
13331                return (v1 > v2) ? -1 : 1;
13332            }
13333            if (r1.isDefault != r2.isDefault) {
13334                return r1.isDefault ? -1 : 1;
13335            }
13336            v1 = r1.match;
13337            v2 = r2.match;
13338            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13339            if (v1 != v2) {
13340                return (v1 > v2) ? -1 : 1;
13341            }
13342            if (r1.system != r2.system) {
13343                return r1.system ? -1 : 1;
13344            }
13345            if (r1.activityInfo != null) {
13346                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13347            }
13348            if (r1.serviceInfo != null) {
13349                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13350            }
13351            if (r1.providerInfo != null) {
13352                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13353            }
13354            return 0;
13355        }
13356    };
13357
13358    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13359            new Comparator<ProviderInfo>() {
13360        public int compare(ProviderInfo p1, ProviderInfo p2) {
13361            final int v1 = p1.initOrder;
13362            final int v2 = p2.initOrder;
13363            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13364        }
13365    };
13366
13367    @Override
13368    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13369            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13370            final int[] userIds, int[] instantUserIds) {
13371        mHandler.post(new Runnable() {
13372            @Override
13373            public void run() {
13374                try {
13375                    final IActivityManager am = ActivityManager.getService();
13376                    if (am == null) return;
13377                    final int[] resolvedUserIds;
13378                    if (userIds == null) {
13379                        resolvedUserIds = am.getRunningUserIds();
13380                    } else {
13381                        resolvedUserIds = userIds;
13382                    }
13383                    doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13384                            resolvedUserIds, false);
13385                    if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) {
13386                        doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13387                                instantUserIds, true);
13388                    }
13389                } catch (RemoteException ex) {
13390                }
13391            }
13392        });
13393    }
13394
13395    @Override
13396    public void notifyPackageAdded(String packageName) {
13397        final PackageListObserver[] observers;
13398        synchronized (mPackages) {
13399            if (mPackageListObservers.size() == 0) {
13400                return;
13401            }
13402            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13403        }
13404        for (int i = observers.length - 1; i >= 0; --i) {
13405            observers[i].onPackageAdded(packageName);
13406        }
13407    }
13408
13409    @Override
13410    public void notifyPackageRemoved(String packageName) {
13411        final PackageListObserver[] observers;
13412        synchronized (mPackages) {
13413            if (mPackageListObservers.size() == 0) {
13414                return;
13415            }
13416            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13417        }
13418        for (int i = observers.length - 1; i >= 0; --i) {
13419            observers[i].onPackageRemoved(packageName);
13420        }
13421    }
13422
13423    /**
13424     * Sends a broadcast for the given action.
13425     * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with
13426     * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows
13427     * the system and applications allowed to see instant applications to receive package
13428     * lifecycle events for instant applications.
13429     */
13430    private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras,
13431            int flags, String targetPkg, IIntentReceiver finishedReceiver,
13432            int[] userIds, boolean isInstantApp)
13433                    throws RemoteException {
13434        for (int id : userIds) {
13435            final Intent intent = new Intent(action,
13436                    pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13437            final String[] requiredPermissions =
13438                    isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null;
13439            if (extras != null) {
13440                intent.putExtras(extras);
13441            }
13442            if (targetPkg != null) {
13443                intent.setPackage(targetPkg);
13444            }
13445            // Modify the UID when posting to other users
13446            int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13447            if (uid > 0 && UserHandle.getUserId(uid) != id) {
13448                uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13449                intent.putExtra(Intent.EXTRA_UID, uid);
13450            }
13451            intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13452            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13453            if (DEBUG_BROADCASTS) {
13454                RuntimeException here = new RuntimeException("here");
13455                here.fillInStackTrace();
13456                Slog.d(TAG, "Sending to user " + id + ": "
13457                        + intent.toShortString(false, true, false, false)
13458                        + " " + intent.getExtras(), here);
13459            }
13460            am.broadcastIntent(null, intent, null, finishedReceiver,
13461                    0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE,
13462                    null, finishedReceiver != null, false, id);
13463        }
13464    }
13465
13466    /**
13467     * Check if the external storage media is available. This is true if there
13468     * is a mounted external storage medium or if the external storage is
13469     * emulated.
13470     */
13471    private boolean isExternalMediaAvailable() {
13472        return mMediaMounted || Environment.isExternalStorageEmulated();
13473    }
13474
13475    @Override
13476    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13477        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13478            return null;
13479        }
13480        if (!isExternalMediaAvailable()) {
13481                // If the external storage is no longer mounted at this point,
13482                // the caller may not have been able to delete all of this
13483                // packages files and can not delete any more.  Bail.
13484            return null;
13485        }
13486        synchronized (mPackages) {
13487            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13488            if (lastPackage != null) {
13489                pkgs.remove(lastPackage);
13490            }
13491            if (pkgs.size() > 0) {
13492                return pkgs.get(0);
13493            }
13494        }
13495        return null;
13496    }
13497
13498    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13499        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13500                userId, andCode ? 1 : 0, packageName);
13501        if (mSystemReady) {
13502            msg.sendToTarget();
13503        } else {
13504            if (mPostSystemReadyMessages == null) {
13505                mPostSystemReadyMessages = new ArrayList<>();
13506            }
13507            mPostSystemReadyMessages.add(msg);
13508        }
13509    }
13510
13511    void startCleaningPackages() {
13512        // reader
13513        if (!isExternalMediaAvailable()) {
13514            return;
13515        }
13516        synchronized (mPackages) {
13517            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13518                return;
13519            }
13520        }
13521        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13522        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13523        IActivityManager am = ActivityManager.getService();
13524        if (am != null) {
13525            int dcsUid = -1;
13526            synchronized (mPackages) {
13527                if (!mDefaultContainerWhitelisted) {
13528                    mDefaultContainerWhitelisted = true;
13529                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13530                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13531                }
13532            }
13533            try {
13534                if (dcsUid > 0) {
13535                    am.backgroundWhitelistUid(dcsUid);
13536                }
13537                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13538                        UserHandle.USER_SYSTEM);
13539            } catch (RemoteException e) {
13540            }
13541        }
13542    }
13543
13544    /**
13545     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13546     * it is acting on behalf on an enterprise or the user).
13547     *
13548     * Note that the ordering of the conditionals in this method is important. The checks we perform
13549     * are as follows, in this order:
13550     *
13551     * 1) If the install is being performed by a system app, we can trust the app to have set the
13552     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13553     *    what it is.
13554     * 2) If the install is being performed by a device or profile owner app, the install reason
13555     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13556     *    set the install reason correctly. If the app targets an older SDK version where install
13557     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13558     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13559     * 3) In all other cases, the install is being performed by a regular app that is neither part
13560     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13561     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13562     *    set to enterprise policy and if so, change it to unknown instead.
13563     */
13564    private int fixUpInstallReason(String installerPackageName, int installerUid,
13565            int installReason) {
13566        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13567                == PERMISSION_GRANTED) {
13568            // If the install is being performed by a system app, we trust that app to have set the
13569            // install reason correctly.
13570            return installReason;
13571        }
13572
13573        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13574            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13575        if (dpm != null) {
13576            ComponentName owner = null;
13577            try {
13578                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13579                if (owner == null) {
13580                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13581                }
13582            } catch (RemoteException e) {
13583            }
13584            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13585                // If the install is being performed by a device or profile owner, the install
13586                // reason should be enterprise policy.
13587                return PackageManager.INSTALL_REASON_POLICY;
13588            }
13589        }
13590
13591        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13592            // If the install is being performed by a regular app (i.e. neither system app nor
13593            // device or profile owner), we have no reason to believe that the app is acting on
13594            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13595            // change it to unknown instead.
13596            return PackageManager.INSTALL_REASON_UNKNOWN;
13597        }
13598
13599        // If the install is being performed by a regular app and the install reason was set to any
13600        // value but enterprise policy, leave the install reason unchanged.
13601        return installReason;
13602    }
13603
13604    void installStage(String packageName, File stagedDir,
13605            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13606            String installerPackageName, int installerUid, UserHandle user,
13607            PackageParser.SigningDetails signingDetails) {
13608        if (DEBUG_EPHEMERAL) {
13609            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13610                Slog.d(TAG, "Ephemeral install of " + packageName);
13611            }
13612        }
13613        final VerificationInfo verificationInfo = new VerificationInfo(
13614                sessionParams.originatingUri, sessionParams.referrerUri,
13615                sessionParams.originatingUid, installerUid);
13616
13617        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
13618
13619        final Message msg = mHandler.obtainMessage(INIT_COPY);
13620        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13621                sessionParams.installReason);
13622        final InstallParams params = new InstallParams(origin, null, observer,
13623                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13624                verificationInfo, user, sessionParams.abiOverride,
13625                sessionParams.grantedRuntimePermissions, signingDetails, installReason);
13626        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13627        msg.obj = params;
13628
13629        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13630                System.identityHashCode(msg.obj));
13631        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13632                System.identityHashCode(msg.obj));
13633
13634        mHandler.sendMessage(msg);
13635    }
13636
13637    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13638            int userId) {
13639        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13640        final boolean isInstantApp = pkgSetting.getInstantApp(userId);
13641        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
13642        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
13643        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
13644                false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds);
13645
13646        // Send a session commit broadcast
13647        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
13648        info.installReason = pkgSetting.getInstallReason(userId);
13649        info.appPackageName = packageName;
13650        sendSessionCommitBroadcast(info, userId);
13651    }
13652
13653    @Override
13654    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
13655            boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) {
13656        if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) {
13657            return;
13658        }
13659        Bundle extras = new Bundle(1);
13660        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13661        final int uid = UserHandle.getUid(
13662                (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId);
13663        extras.putInt(Intent.EXTRA_UID, uid);
13664
13665        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13666                packageName, extras, 0, null, null, userIds, instantUserIds);
13667        if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) {
13668            mHandler.post(() -> {
13669                        for (int userId : userIds) {
13670                            sendBootCompletedBroadcastToSystemApp(
13671                                    packageName, includeStopped, userId);
13672                        }
13673                    }
13674            );
13675        }
13676    }
13677
13678    /**
13679     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13680     * automatically without needing an explicit launch.
13681     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13682     */
13683    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
13684            int userId) {
13685        // If user is not running, the app didn't miss any broadcast
13686        if (!mUserManagerInternal.isUserRunning(userId)) {
13687            return;
13688        }
13689        final IActivityManager am = ActivityManager.getService();
13690        try {
13691            // Deliver LOCKED_BOOT_COMPLETED first
13692            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13693                    .setPackage(packageName);
13694            if (includeStopped) {
13695                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13696            }
13697            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13698            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13699                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13700
13701            // Deliver BOOT_COMPLETED only if user is unlocked
13702            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13703                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13704                if (includeStopped) {
13705                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13706                }
13707                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13708                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13709            }
13710        } catch (RemoteException e) {
13711            throw e.rethrowFromSystemServer();
13712        }
13713    }
13714
13715    @Override
13716    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13717            int userId) {
13718        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13719        PackageSetting pkgSetting;
13720        final int callingUid = Binder.getCallingUid();
13721        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13722                true /* requireFullPermission */, true /* checkShell */,
13723                "setApplicationHiddenSetting for user " + userId);
13724
13725        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13726            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13727            return false;
13728        }
13729
13730        long callingId = Binder.clearCallingIdentity();
13731        try {
13732            boolean sendAdded = false;
13733            boolean sendRemoved = false;
13734            // writer
13735            synchronized (mPackages) {
13736                pkgSetting = mSettings.mPackages.get(packageName);
13737                if (pkgSetting == null) {
13738                    return false;
13739                }
13740                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13741                    return false;
13742                }
13743                // Do not allow "android" is being disabled
13744                if ("android".equals(packageName)) {
13745                    Slog.w(TAG, "Cannot hide package: android");
13746                    return false;
13747                }
13748                // Cannot hide static shared libs as they are considered
13749                // a part of the using app (emulating static linking). Also
13750                // static libs are installed always on internal storage.
13751                PackageParser.Package pkg = mPackages.get(packageName);
13752                if (pkg != null && pkg.staticSharedLibName != null) {
13753                    Slog.w(TAG, "Cannot hide package: " + packageName
13754                            + " providing static shared library: "
13755                            + pkg.staticSharedLibName);
13756                    return false;
13757                }
13758                // Only allow protected packages to hide themselves.
13759                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
13760                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13761                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13762                    return false;
13763                }
13764
13765                if (pkgSetting.getHidden(userId) != hidden) {
13766                    pkgSetting.setHidden(hidden, userId);
13767                    mSettings.writePackageRestrictionsLPr(userId);
13768                    if (hidden) {
13769                        sendRemoved = true;
13770                    } else {
13771                        sendAdded = true;
13772                    }
13773                }
13774            }
13775            if (sendAdded) {
13776                sendPackageAddedForUser(packageName, pkgSetting, userId);
13777                return true;
13778            }
13779            if (sendRemoved) {
13780                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13781                        "hiding pkg");
13782                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13783                return true;
13784            }
13785        } finally {
13786            Binder.restoreCallingIdentity(callingId);
13787        }
13788        return false;
13789    }
13790
13791    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13792            int userId) {
13793        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13794        info.removedPackage = packageName;
13795        info.installerPackageName = pkgSetting.installerPackageName;
13796        info.removedUsers = new int[] {userId};
13797        info.broadcastUsers = new int[] {userId};
13798        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13799        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13800    }
13801
13802    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13803        if (pkgList.length > 0) {
13804            Bundle extras = new Bundle(1);
13805            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13806
13807            sendPackageBroadcast(
13808                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13809                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13810                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13811                    new int[] {userId}, null);
13812        }
13813    }
13814
13815    /**
13816     * Returns true if application is not found or there was an error. Otherwise it returns
13817     * the hidden state of the package for the given user.
13818     */
13819    @Override
13820    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13821        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13822        final int callingUid = Binder.getCallingUid();
13823        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13824                true /* requireFullPermission */, false /* checkShell */,
13825                "getApplicationHidden for user " + userId);
13826        PackageSetting ps;
13827        long callingId = Binder.clearCallingIdentity();
13828        try {
13829            // writer
13830            synchronized (mPackages) {
13831                ps = mSettings.mPackages.get(packageName);
13832                if (ps == null) {
13833                    return true;
13834                }
13835                if (filterAppAccessLPr(ps, callingUid, userId)) {
13836                    return true;
13837                }
13838                return ps.getHidden(userId);
13839            }
13840        } finally {
13841            Binder.restoreCallingIdentity(callingId);
13842        }
13843    }
13844
13845    /**
13846     * @hide
13847     */
13848    @Override
13849    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13850            int installReason) {
13851        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13852                null);
13853        PackageSetting pkgSetting;
13854        final int callingUid = Binder.getCallingUid();
13855        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13856                true /* requireFullPermission */, true /* checkShell */,
13857                "installExistingPackage for user " + userId);
13858        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13859            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13860        }
13861
13862        long callingId = Binder.clearCallingIdentity();
13863        try {
13864            boolean installed = false;
13865            final boolean instantApp =
13866                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13867            final boolean fullApp =
13868                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13869
13870            // writer
13871            synchronized (mPackages) {
13872                pkgSetting = mSettings.mPackages.get(packageName);
13873                if (pkgSetting == null) {
13874                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13875                }
13876                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
13877                    // only allow the existing package to be used if it's installed as a full
13878                    // application for at least one user
13879                    boolean installAllowed = false;
13880                    for (int checkUserId : sUserManager.getUserIds()) {
13881                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
13882                        if (installAllowed) {
13883                            break;
13884                        }
13885                    }
13886                    if (!installAllowed) {
13887                        return PackageManager.INSTALL_FAILED_INVALID_URI;
13888                    }
13889                }
13890                if (!pkgSetting.getInstalled(userId)) {
13891                    pkgSetting.setInstalled(true, userId);
13892                    pkgSetting.setHidden(false, userId);
13893                    pkgSetting.setInstallReason(installReason, userId);
13894                    mSettings.writePackageRestrictionsLPr(userId);
13895                    mSettings.writeKernelMappingLPr(pkgSetting);
13896                    installed = true;
13897                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13898                    // upgrade app from instant to full; we don't allow app downgrade
13899                    installed = true;
13900                }
13901                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13902            }
13903
13904            if (installed) {
13905                if (pkgSetting.pkg != null) {
13906                    synchronized (mInstallLock) {
13907                        // We don't need to freeze for a brand new install
13908                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13909                    }
13910                }
13911                sendPackageAddedForUser(packageName, pkgSetting, userId);
13912                synchronized (mPackages) {
13913                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
13914                }
13915            }
13916        } finally {
13917            Binder.restoreCallingIdentity(callingId);
13918        }
13919
13920        return PackageManager.INSTALL_SUCCEEDED;
13921    }
13922
13923    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13924            boolean instantApp, boolean fullApp) {
13925        // no state specified; do nothing
13926        if (!instantApp && !fullApp) {
13927            return;
13928        }
13929        if (userId != UserHandle.USER_ALL) {
13930            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13931                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13932            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13933                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13934            }
13935        } else {
13936            for (int currentUserId : sUserManager.getUserIds()) {
13937                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13938                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13939                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13940                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13941                }
13942            }
13943        }
13944    }
13945
13946    boolean isUserRestricted(int userId, String restrictionKey) {
13947        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13948        if (restrictions.getBoolean(restrictionKey, false)) {
13949            Log.w(TAG, "User is restricted: " + restrictionKey);
13950            return true;
13951        }
13952        return false;
13953    }
13954
13955    @Override
13956    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13957            int userId) {
13958        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13959        final int callingUid = Binder.getCallingUid();
13960        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13961                true /* requireFullPermission */, true /* checkShell */,
13962                "setPackagesSuspended for user " + userId);
13963
13964        if (ArrayUtils.isEmpty(packageNames)) {
13965            return packageNames;
13966        }
13967
13968        // List of package names for whom the suspended state has changed.
13969        List<String> changedPackages = new ArrayList<>(packageNames.length);
13970        // List of package names for whom the suspended state is not set as requested in this
13971        // method.
13972        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13973        long callingId = Binder.clearCallingIdentity();
13974        try {
13975            for (int i = 0; i < packageNames.length; i++) {
13976                String packageName = packageNames[i];
13977                boolean changed = false;
13978                final int appId;
13979                synchronized (mPackages) {
13980                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13981                    if (pkgSetting == null
13982                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13983                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13984                                + "\". Skipping suspending/un-suspending.");
13985                        unactionedPackages.add(packageName);
13986                        continue;
13987                    }
13988                    appId = pkgSetting.appId;
13989                    if (pkgSetting.getSuspended(userId) != suspended) {
13990                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13991                            unactionedPackages.add(packageName);
13992                            continue;
13993                        }
13994                        pkgSetting.setSuspended(suspended, userId);
13995                        mSettings.writePackageRestrictionsLPr(userId);
13996                        changed = true;
13997                        changedPackages.add(packageName);
13998                    }
13999                }
14000
14001                if (changed && suspended) {
14002                    killApplication(packageName, UserHandle.getUid(userId, appId),
14003                            "suspending package");
14004                }
14005            }
14006        } finally {
14007            Binder.restoreCallingIdentity(callingId);
14008        }
14009
14010        if (!changedPackages.isEmpty()) {
14011            sendPackagesSuspendedForUser(changedPackages.toArray(
14012                    new String[changedPackages.size()]), userId, suspended);
14013        }
14014
14015        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14016    }
14017
14018    @Override
14019    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14020        final int callingUid = Binder.getCallingUid();
14021        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14022                true /* requireFullPermission */, false /* checkShell */,
14023                "isPackageSuspendedForUser for user " + userId);
14024        synchronized (mPackages) {
14025            final PackageSetting ps = mSettings.mPackages.get(packageName);
14026            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14027                throw new IllegalArgumentException("Unknown target package: " + packageName);
14028            }
14029            return ps.getSuspended(userId);
14030        }
14031    }
14032
14033    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14034        if (isPackageDeviceAdmin(packageName, userId)) {
14035            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14036                    + "\": has an active device admin");
14037            return false;
14038        }
14039
14040        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14041        if (packageName.equals(activeLauncherPackageName)) {
14042            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14043                    + "\": contains the active launcher");
14044            return false;
14045        }
14046
14047        if (packageName.equals(mRequiredInstallerPackage)) {
14048            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14049                    + "\": required for package installation");
14050            return false;
14051        }
14052
14053        if (packageName.equals(mRequiredUninstallerPackage)) {
14054            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14055                    + "\": required for package uninstallation");
14056            return false;
14057        }
14058
14059        if (packageName.equals(mRequiredVerifierPackage)) {
14060            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14061                    + "\": required for package verification");
14062            return false;
14063        }
14064
14065        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14066            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14067                    + "\": is the default dialer");
14068            return false;
14069        }
14070
14071        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14072            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14073                    + "\": protected package");
14074            return false;
14075        }
14076
14077        // Cannot suspend static shared libs as they are considered
14078        // a part of the using app (emulating static linking). Also
14079        // static libs are installed always on internal storage.
14080        PackageParser.Package pkg = mPackages.get(packageName);
14081        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14082            Slog.w(TAG, "Cannot suspend package: " + packageName
14083                    + " providing static shared library: "
14084                    + pkg.staticSharedLibName);
14085            return false;
14086        }
14087
14088        return true;
14089    }
14090
14091    private String getActiveLauncherPackageName(int userId) {
14092        Intent intent = new Intent(Intent.ACTION_MAIN);
14093        intent.addCategory(Intent.CATEGORY_HOME);
14094        ResolveInfo resolveInfo = resolveIntent(
14095                intent,
14096                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14097                PackageManager.MATCH_DEFAULT_ONLY,
14098                userId);
14099
14100        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14101    }
14102
14103    private String getDefaultDialerPackageName(int userId) {
14104        synchronized (mPackages) {
14105            return mSettings.getDefaultDialerPackageNameLPw(userId);
14106        }
14107    }
14108
14109    @Override
14110    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14111        mContext.enforceCallingOrSelfPermission(
14112                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14113                "Only package verification agents can verify applications");
14114
14115        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14116        final PackageVerificationResponse response = new PackageVerificationResponse(
14117                verificationCode, Binder.getCallingUid());
14118        msg.arg1 = id;
14119        msg.obj = response;
14120        mHandler.sendMessage(msg);
14121    }
14122
14123    @Override
14124    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14125            long millisecondsToDelay) {
14126        mContext.enforceCallingOrSelfPermission(
14127                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14128                "Only package verification agents can extend verification timeouts");
14129
14130        final PackageVerificationState state = mPendingVerification.get(id);
14131        final PackageVerificationResponse response = new PackageVerificationResponse(
14132                verificationCodeAtTimeout, Binder.getCallingUid());
14133
14134        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14135            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14136        }
14137        if (millisecondsToDelay < 0) {
14138            millisecondsToDelay = 0;
14139        }
14140        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14141                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14142            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14143        }
14144
14145        if ((state != null) && !state.timeoutExtended()) {
14146            state.extendTimeout();
14147
14148            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14149            msg.arg1 = id;
14150            msg.obj = response;
14151            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14152        }
14153    }
14154
14155    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14156            int verificationCode, UserHandle user) {
14157        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14158        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14159        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14160        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14161        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14162
14163        mContext.sendBroadcastAsUser(intent, user,
14164                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14165    }
14166
14167    private ComponentName matchComponentForVerifier(String packageName,
14168            List<ResolveInfo> receivers) {
14169        ActivityInfo targetReceiver = null;
14170
14171        final int NR = receivers.size();
14172        for (int i = 0; i < NR; i++) {
14173            final ResolveInfo info = receivers.get(i);
14174            if (info.activityInfo == null) {
14175                continue;
14176            }
14177
14178            if (packageName.equals(info.activityInfo.packageName)) {
14179                targetReceiver = info.activityInfo;
14180                break;
14181            }
14182        }
14183
14184        if (targetReceiver == null) {
14185            return null;
14186        }
14187
14188        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14189    }
14190
14191    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14192            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14193        if (pkgInfo.verifiers.length == 0) {
14194            return null;
14195        }
14196
14197        final int N = pkgInfo.verifiers.length;
14198        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14199        for (int i = 0; i < N; i++) {
14200            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14201
14202            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14203                    receivers);
14204            if (comp == null) {
14205                continue;
14206            }
14207
14208            final int verifierUid = getUidForVerifier(verifierInfo);
14209            if (verifierUid == -1) {
14210                continue;
14211            }
14212
14213            if (DEBUG_VERIFY) {
14214                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14215                        + " with the correct signature");
14216            }
14217            sufficientVerifiers.add(comp);
14218            verificationState.addSufficientVerifier(verifierUid);
14219        }
14220
14221        return sufficientVerifiers;
14222    }
14223
14224    private int getUidForVerifier(VerifierInfo verifierInfo) {
14225        synchronized (mPackages) {
14226            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14227            if (pkg == null) {
14228                return -1;
14229            } else if (pkg.mSigningDetails.signatures.length != 1) {
14230                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14231                        + " has more than one signature; ignoring");
14232                return -1;
14233            }
14234
14235            /*
14236             * If the public key of the package's signature does not match
14237             * our expected public key, then this is a different package and
14238             * we should skip.
14239             */
14240
14241            final byte[] expectedPublicKey;
14242            try {
14243                final Signature verifierSig = pkg.mSigningDetails.signatures[0];
14244                final PublicKey publicKey = verifierSig.getPublicKey();
14245                expectedPublicKey = publicKey.getEncoded();
14246            } catch (CertificateException e) {
14247                return -1;
14248            }
14249
14250            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14251
14252            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14253                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14254                        + " does not have the expected public key; ignoring");
14255                return -1;
14256            }
14257
14258            return pkg.applicationInfo.uid;
14259        }
14260    }
14261
14262    @Override
14263    public void finishPackageInstall(int token, boolean didLaunch) {
14264        enforceSystemOrRoot("Only the system is allowed to finish installs");
14265
14266        if (DEBUG_INSTALL) {
14267            Slog.v(TAG, "BM finishing package install for " + token);
14268        }
14269        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14270
14271        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14272        mHandler.sendMessage(msg);
14273    }
14274
14275    /**
14276     * Get the verification agent timeout.  Used for both the APK verifier and the
14277     * intent filter verifier.
14278     *
14279     * @return verification timeout in milliseconds
14280     */
14281    private long getVerificationTimeout() {
14282        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14283                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14284                DEFAULT_VERIFICATION_TIMEOUT);
14285    }
14286
14287    /**
14288     * Get the default verification agent response code.
14289     *
14290     * @return default verification response code
14291     */
14292    private int getDefaultVerificationResponse(UserHandle user) {
14293        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14294            return PackageManager.VERIFICATION_REJECT;
14295        }
14296        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14297                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14298                DEFAULT_VERIFICATION_RESPONSE);
14299    }
14300
14301    /**
14302     * Check whether or not package verification has been enabled.
14303     *
14304     * @return true if verification should be performed
14305     */
14306    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14307        if (!DEFAULT_VERIFY_ENABLE) {
14308            return false;
14309        }
14310
14311        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14312
14313        // Check if installing from ADB
14314        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14315            // Do not run verification in a test harness environment
14316            if (ActivityManager.isRunningInTestHarness()) {
14317                return false;
14318            }
14319            if (ensureVerifyAppsEnabled) {
14320                return true;
14321            }
14322            // Check if the developer does not want package verification for ADB installs
14323            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14324                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14325                return false;
14326            }
14327        } else {
14328            // only when not installed from ADB, skip verification for instant apps when
14329            // the installer and verifier are the same.
14330            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14331                if (mInstantAppInstallerActivity != null
14332                        && mInstantAppInstallerActivity.packageName.equals(
14333                                mRequiredVerifierPackage)) {
14334                    try {
14335                        mContext.getSystemService(AppOpsManager.class)
14336                                .checkPackage(installerUid, mRequiredVerifierPackage);
14337                        if (DEBUG_VERIFY) {
14338                            Slog.i(TAG, "disable verification for instant app");
14339                        }
14340                        return false;
14341                    } catch (SecurityException ignore) { }
14342                }
14343            }
14344        }
14345
14346        if (ensureVerifyAppsEnabled) {
14347            return true;
14348        }
14349
14350        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14351                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14352    }
14353
14354    @Override
14355    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14356            throws RemoteException {
14357        mContext.enforceCallingOrSelfPermission(
14358                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14359                "Only intentfilter verification agents can verify applications");
14360
14361        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14362        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14363                Binder.getCallingUid(), verificationCode, failedDomains);
14364        msg.arg1 = id;
14365        msg.obj = response;
14366        mHandler.sendMessage(msg);
14367    }
14368
14369    @Override
14370    public int getIntentVerificationStatus(String packageName, int userId) {
14371        final int callingUid = Binder.getCallingUid();
14372        if (UserHandle.getUserId(callingUid) != userId) {
14373            mContext.enforceCallingOrSelfPermission(
14374                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14375                    "getIntentVerificationStatus" + userId);
14376        }
14377        if (getInstantAppPackageName(callingUid) != null) {
14378            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14379        }
14380        synchronized (mPackages) {
14381            final PackageSetting ps = mSettings.mPackages.get(packageName);
14382            if (ps == null
14383                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14384                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14385            }
14386            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14387        }
14388    }
14389
14390    @Override
14391    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14392        mContext.enforceCallingOrSelfPermission(
14393                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14394
14395        boolean result = false;
14396        synchronized (mPackages) {
14397            final PackageSetting ps = mSettings.mPackages.get(packageName);
14398            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14399                return false;
14400            }
14401            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14402        }
14403        if (result) {
14404            scheduleWritePackageRestrictionsLocked(userId);
14405        }
14406        return result;
14407    }
14408
14409    @Override
14410    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14411            String packageName) {
14412        final int callingUid = Binder.getCallingUid();
14413        if (getInstantAppPackageName(callingUid) != null) {
14414            return ParceledListSlice.emptyList();
14415        }
14416        synchronized (mPackages) {
14417            final PackageSetting ps = mSettings.mPackages.get(packageName);
14418            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14419                return ParceledListSlice.emptyList();
14420            }
14421            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14422        }
14423    }
14424
14425    @Override
14426    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14427        if (TextUtils.isEmpty(packageName)) {
14428            return ParceledListSlice.emptyList();
14429        }
14430        final int callingUid = Binder.getCallingUid();
14431        final int callingUserId = UserHandle.getUserId(callingUid);
14432        synchronized (mPackages) {
14433            PackageParser.Package pkg = mPackages.get(packageName);
14434            if (pkg == null || pkg.activities == null) {
14435                return ParceledListSlice.emptyList();
14436            }
14437            if (pkg.mExtras == null) {
14438                return ParceledListSlice.emptyList();
14439            }
14440            final PackageSetting ps = (PackageSetting) pkg.mExtras;
14441            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14442                return ParceledListSlice.emptyList();
14443            }
14444            final int count = pkg.activities.size();
14445            ArrayList<IntentFilter> result = new ArrayList<>();
14446            for (int n=0; n<count; n++) {
14447                PackageParser.Activity activity = pkg.activities.get(n);
14448                if (activity.intents != null && activity.intents.size() > 0) {
14449                    result.addAll(activity.intents);
14450                }
14451            }
14452            return new ParceledListSlice<>(result);
14453        }
14454    }
14455
14456    @Override
14457    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14458        mContext.enforceCallingOrSelfPermission(
14459                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14460        if (UserHandle.getCallingUserId() != userId) {
14461            mContext.enforceCallingOrSelfPermission(
14462                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14463        }
14464
14465        synchronized (mPackages) {
14466            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14467            if (packageName != null) {
14468                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
14469                        packageName, userId);
14470            }
14471            return result;
14472        }
14473    }
14474
14475    @Override
14476    public String getDefaultBrowserPackageName(int userId) {
14477        if (UserHandle.getCallingUserId() != userId) {
14478            mContext.enforceCallingOrSelfPermission(
14479                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14480        }
14481        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14482            return null;
14483        }
14484        synchronized (mPackages) {
14485            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14486        }
14487    }
14488
14489    /**
14490     * Get the "allow unknown sources" setting.
14491     *
14492     * @return the current "allow unknown sources" setting
14493     */
14494    private int getUnknownSourcesSettings() {
14495        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14496                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14497                -1);
14498    }
14499
14500    @Override
14501    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14502        final int callingUid = Binder.getCallingUid();
14503        if (getInstantAppPackageName(callingUid) != null) {
14504            return;
14505        }
14506        // writer
14507        synchronized (mPackages) {
14508            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14509            if (targetPackageSetting == null
14510                    || filterAppAccessLPr(
14511                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
14512                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14513            }
14514
14515            PackageSetting installerPackageSetting;
14516            if (installerPackageName != null) {
14517                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14518                if (installerPackageSetting == null) {
14519                    throw new IllegalArgumentException("Unknown installer package: "
14520                            + installerPackageName);
14521                }
14522            } else {
14523                installerPackageSetting = null;
14524            }
14525
14526            Signature[] callerSignature;
14527            Object obj = mSettings.getUserIdLPr(callingUid);
14528            if (obj != null) {
14529                if (obj instanceof SharedUserSetting) {
14530                    callerSignature =
14531                            ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
14532                } else if (obj instanceof PackageSetting) {
14533                    callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures;
14534                } else {
14535                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
14536                }
14537            } else {
14538                throw new SecurityException("Unknown calling UID: " + callingUid);
14539            }
14540
14541            // Verify: can't set installerPackageName to a package that is
14542            // not signed with the same cert as the caller.
14543            if (installerPackageSetting != null) {
14544                if (compareSignatures(callerSignature,
14545                        installerPackageSetting.signatures.mSigningDetails.signatures)
14546                        != PackageManager.SIGNATURE_MATCH) {
14547                    throw new SecurityException(
14548                            "Caller does not have same cert as new installer package "
14549                            + installerPackageName);
14550                }
14551            }
14552
14553            // Verify: if target already has an installer package, it must
14554            // be signed with the same cert as the caller.
14555            if (targetPackageSetting.installerPackageName != null) {
14556                PackageSetting setting = mSettings.mPackages.get(
14557                        targetPackageSetting.installerPackageName);
14558                // If the currently set package isn't valid, then it's always
14559                // okay to change it.
14560                if (setting != null) {
14561                    if (compareSignatures(callerSignature,
14562                            setting.signatures.mSigningDetails.signatures)
14563                            != PackageManager.SIGNATURE_MATCH) {
14564                        throw new SecurityException(
14565                                "Caller does not have same cert as old installer package "
14566                                + targetPackageSetting.installerPackageName);
14567                    }
14568                }
14569            }
14570
14571            // Okay!
14572            targetPackageSetting.installerPackageName = installerPackageName;
14573            if (installerPackageName != null) {
14574                mSettings.mInstallerPackages.add(installerPackageName);
14575            }
14576            scheduleWriteSettingsLocked();
14577        }
14578    }
14579
14580    @Override
14581    public void setApplicationCategoryHint(String packageName, int categoryHint,
14582            String callerPackageName) {
14583        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14584            throw new SecurityException("Instant applications don't have access to this method");
14585        }
14586        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14587                callerPackageName);
14588        synchronized (mPackages) {
14589            PackageSetting ps = mSettings.mPackages.get(packageName);
14590            if (ps == null) {
14591                throw new IllegalArgumentException("Unknown target package " + packageName);
14592            }
14593            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14594                throw new IllegalArgumentException("Unknown target package " + packageName);
14595            }
14596            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14597                throw new IllegalArgumentException("Calling package " + callerPackageName
14598                        + " is not installer for " + packageName);
14599            }
14600
14601            if (ps.categoryHint != categoryHint) {
14602                ps.categoryHint = categoryHint;
14603                scheduleWriteSettingsLocked();
14604            }
14605        }
14606    }
14607
14608    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14609        // Queue up an async operation since the package installation may take a little while.
14610        mHandler.post(new Runnable() {
14611            public void run() {
14612                mHandler.removeCallbacks(this);
14613                 // Result object to be returned
14614                PackageInstalledInfo res = new PackageInstalledInfo();
14615                res.setReturnCode(currentStatus);
14616                res.uid = -1;
14617                res.pkg = null;
14618                res.removedInfo = null;
14619                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14620                    args.doPreInstall(res.returnCode);
14621                    synchronized (mInstallLock) {
14622                        installPackageTracedLI(args, res);
14623                    }
14624                    args.doPostInstall(res.returnCode, res.uid);
14625                }
14626
14627                // A restore should be performed at this point if (a) the install
14628                // succeeded, (b) the operation is not an update, and (c) the new
14629                // package has not opted out of backup participation.
14630                final boolean update = res.removedInfo != null
14631                        && res.removedInfo.removedPackage != null;
14632                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14633                boolean doRestore = !update
14634                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14635
14636                // Set up the post-install work request bookkeeping.  This will be used
14637                // and cleaned up by the post-install event handling regardless of whether
14638                // there's a restore pass performed.  Token values are >= 1.
14639                int token;
14640                if (mNextInstallToken < 0) mNextInstallToken = 1;
14641                token = mNextInstallToken++;
14642
14643                PostInstallData data = new PostInstallData(args, res);
14644                mRunningInstalls.put(token, data);
14645                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14646
14647                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14648                    // Pass responsibility to the Backup Manager.  It will perform a
14649                    // restore if appropriate, then pass responsibility back to the
14650                    // Package Manager to run the post-install observer callbacks
14651                    // and broadcasts.
14652                    IBackupManager bm = IBackupManager.Stub.asInterface(
14653                            ServiceManager.getService(Context.BACKUP_SERVICE));
14654                    if (bm != null) {
14655                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14656                                + " to BM for possible restore");
14657                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14658                        try {
14659                            // TODO: http://b/22388012
14660                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14661                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14662                            } else {
14663                                doRestore = false;
14664                            }
14665                        } catch (RemoteException e) {
14666                            // can't happen; the backup manager is local
14667                        } catch (Exception e) {
14668                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14669                            doRestore = false;
14670                        }
14671                    } else {
14672                        Slog.e(TAG, "Backup Manager not found!");
14673                        doRestore = false;
14674                    }
14675                }
14676
14677                if (!doRestore) {
14678                    // No restore possible, or the Backup Manager was mysteriously not
14679                    // available -- just fire the post-install work request directly.
14680                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14681
14682                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14683
14684                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14685                    mHandler.sendMessage(msg);
14686                }
14687            }
14688        });
14689    }
14690
14691    /**
14692     * Callback from PackageSettings whenever an app is first transitioned out of the
14693     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14694     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14695     * here whether the app is the target of an ongoing install, and only send the
14696     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14697     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14698     * handling.
14699     */
14700    void notifyFirstLaunch(final String packageName, final String installerPackage,
14701            final int userId) {
14702        // Serialize this with the rest of the install-process message chain.  In the
14703        // restore-at-install case, this Runnable will necessarily run before the
14704        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14705        // are coherent.  In the non-restore case, the app has already completed install
14706        // and been launched through some other means, so it is not in a problematic
14707        // state for observers to see the FIRST_LAUNCH signal.
14708        mHandler.post(new Runnable() {
14709            @Override
14710            public void run() {
14711                for (int i = 0; i < mRunningInstalls.size(); i++) {
14712                    final PostInstallData data = mRunningInstalls.valueAt(i);
14713                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14714                        continue;
14715                    }
14716                    if (packageName.equals(data.res.pkg.applicationInfo.packageName)) {
14717                        // right package; but is it for the right user?
14718                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14719                            if (userId == data.res.newUsers[uIndex]) {
14720                                if (DEBUG_BACKUP) {
14721                                    Slog.i(TAG, "Package " + packageName
14722                                            + " being restored so deferring FIRST_LAUNCH");
14723                                }
14724                                return;
14725                            }
14726                        }
14727                    }
14728                }
14729                // didn't find it, so not being restored
14730                if (DEBUG_BACKUP) {
14731                    Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH");
14732                }
14733                final boolean isInstantApp = isInstantApp(packageName, userId);
14734                final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
14735                final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
14736                sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds);
14737            }
14738        });
14739    }
14740
14741    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg,
14742            int[] userIds, int[] instantUserIds) {
14743        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14744                installerPkg, null, userIds, instantUserIds);
14745    }
14746
14747    private abstract class HandlerParams {
14748        private static final int MAX_RETRIES = 4;
14749
14750        /**
14751         * Number of times startCopy() has been attempted and had a non-fatal
14752         * error.
14753         */
14754        private int mRetries = 0;
14755
14756        /** User handle for the user requesting the information or installation. */
14757        private final UserHandle mUser;
14758        String traceMethod;
14759        int traceCookie;
14760
14761        HandlerParams(UserHandle user) {
14762            mUser = user;
14763        }
14764
14765        UserHandle getUser() {
14766            return mUser;
14767        }
14768
14769        HandlerParams setTraceMethod(String traceMethod) {
14770            this.traceMethod = traceMethod;
14771            return this;
14772        }
14773
14774        HandlerParams setTraceCookie(int traceCookie) {
14775            this.traceCookie = traceCookie;
14776            return this;
14777        }
14778
14779        final boolean startCopy() {
14780            boolean res;
14781            try {
14782                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14783
14784                if (++mRetries > MAX_RETRIES) {
14785                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14786                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14787                    handleServiceError();
14788                    return false;
14789                } else {
14790                    handleStartCopy();
14791                    res = true;
14792                }
14793            } catch (RemoteException e) {
14794                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14795                mHandler.sendEmptyMessage(MCS_RECONNECT);
14796                res = false;
14797            }
14798            handleReturnCode();
14799            return res;
14800        }
14801
14802        final void serviceError() {
14803            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14804            handleServiceError();
14805            handleReturnCode();
14806        }
14807
14808        abstract void handleStartCopy() throws RemoteException;
14809        abstract void handleServiceError();
14810        abstract void handleReturnCode();
14811    }
14812
14813    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14814        for (File path : paths) {
14815            try {
14816                mcs.clearDirectory(path.getAbsolutePath());
14817            } catch (RemoteException e) {
14818            }
14819        }
14820    }
14821
14822    static class OriginInfo {
14823        /**
14824         * Location where install is coming from, before it has been
14825         * copied/renamed into place. This could be a single monolithic APK
14826         * file, or a cluster directory. This location may be untrusted.
14827         */
14828        final File file;
14829
14830        /**
14831         * Flag indicating that {@link #file} or {@link #cid} has already been
14832         * staged, meaning downstream users don't need to defensively copy the
14833         * contents.
14834         */
14835        final boolean staged;
14836
14837        /**
14838         * Flag indicating that {@link #file} or {@link #cid} is an already
14839         * installed app that is being moved.
14840         */
14841        final boolean existing;
14842
14843        final String resolvedPath;
14844        final File resolvedFile;
14845
14846        static OriginInfo fromNothing() {
14847            return new OriginInfo(null, false, false);
14848        }
14849
14850        static OriginInfo fromUntrustedFile(File file) {
14851            return new OriginInfo(file, false, false);
14852        }
14853
14854        static OriginInfo fromExistingFile(File file) {
14855            return new OriginInfo(file, false, true);
14856        }
14857
14858        static OriginInfo fromStagedFile(File file) {
14859            return new OriginInfo(file, true, false);
14860        }
14861
14862        private OriginInfo(File file, boolean staged, boolean existing) {
14863            this.file = file;
14864            this.staged = staged;
14865            this.existing = existing;
14866
14867            if (file != null) {
14868                resolvedPath = file.getAbsolutePath();
14869                resolvedFile = file;
14870            } else {
14871                resolvedPath = null;
14872                resolvedFile = null;
14873            }
14874        }
14875    }
14876
14877    static class MoveInfo {
14878        final int moveId;
14879        final String fromUuid;
14880        final String toUuid;
14881        final String packageName;
14882        final String dataAppName;
14883        final int appId;
14884        final String seinfo;
14885        final int targetSdkVersion;
14886
14887        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14888                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14889            this.moveId = moveId;
14890            this.fromUuid = fromUuid;
14891            this.toUuid = toUuid;
14892            this.packageName = packageName;
14893            this.dataAppName = dataAppName;
14894            this.appId = appId;
14895            this.seinfo = seinfo;
14896            this.targetSdkVersion = targetSdkVersion;
14897        }
14898    }
14899
14900    static class VerificationInfo {
14901        /** A constant used to indicate that a uid value is not present. */
14902        public static final int NO_UID = -1;
14903
14904        /** URI referencing where the package was downloaded from. */
14905        final Uri originatingUri;
14906
14907        /** HTTP referrer URI associated with the originatingURI. */
14908        final Uri referrer;
14909
14910        /** UID of the application that the install request originated from. */
14911        final int originatingUid;
14912
14913        /** UID of application requesting the install */
14914        final int installerUid;
14915
14916        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14917            this.originatingUri = originatingUri;
14918            this.referrer = referrer;
14919            this.originatingUid = originatingUid;
14920            this.installerUid = installerUid;
14921        }
14922    }
14923
14924    class InstallParams extends HandlerParams {
14925        final OriginInfo origin;
14926        final MoveInfo move;
14927        final IPackageInstallObserver2 observer;
14928        int installFlags;
14929        final String installerPackageName;
14930        final String volumeUuid;
14931        private InstallArgs mArgs;
14932        private int mRet;
14933        final String packageAbiOverride;
14934        final String[] grantedRuntimePermissions;
14935        final VerificationInfo verificationInfo;
14936        final PackageParser.SigningDetails signingDetails;
14937        final int installReason;
14938
14939        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14940                int installFlags, String installerPackageName, String volumeUuid,
14941                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14942                String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) {
14943            super(user);
14944            this.origin = origin;
14945            this.move = move;
14946            this.observer = observer;
14947            this.installFlags = installFlags;
14948            this.installerPackageName = installerPackageName;
14949            this.volumeUuid = volumeUuid;
14950            this.verificationInfo = verificationInfo;
14951            this.packageAbiOverride = packageAbiOverride;
14952            this.grantedRuntimePermissions = grantedPermissions;
14953            this.signingDetails = signingDetails;
14954            this.installReason = installReason;
14955        }
14956
14957        @Override
14958        public String toString() {
14959            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14960                    + " file=" + origin.file + "}";
14961        }
14962
14963        private int installLocationPolicy(PackageInfoLite pkgLite) {
14964            String packageName = pkgLite.packageName;
14965            int installLocation = pkgLite.installLocation;
14966            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14967            // reader
14968            synchronized (mPackages) {
14969                // Currently installed package which the new package is attempting to replace or
14970                // null if no such package is installed.
14971                PackageParser.Package installedPkg = mPackages.get(packageName);
14972                // Package which currently owns the data which the new package will own if installed.
14973                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14974                // will be null whereas dataOwnerPkg will contain information about the package
14975                // which was uninstalled while keeping its data.
14976                PackageParser.Package dataOwnerPkg = installedPkg;
14977                if (dataOwnerPkg  == null) {
14978                    PackageSetting ps = mSettings.mPackages.get(packageName);
14979                    if (ps != null) {
14980                        dataOwnerPkg = ps.pkg;
14981                    }
14982                }
14983
14984                if (dataOwnerPkg != null) {
14985                    // If installed, the package will get access to data left on the device by its
14986                    // predecessor. As a security measure, this is permited only if this is not a
14987                    // version downgrade or if the predecessor package is marked as debuggable and
14988                    // a downgrade is explicitly requested.
14989                    //
14990                    // On debuggable platform builds, downgrades are permitted even for
14991                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14992                    // not offer security guarantees and thus it's OK to disable some security
14993                    // mechanisms to make debugging/testing easier on those builds. However, even on
14994                    // debuggable builds downgrades of packages are permitted only if requested via
14995                    // installFlags. This is because we aim to keep the behavior of debuggable
14996                    // platform builds as close as possible to the behavior of non-debuggable
14997                    // platform builds.
14998                    final boolean downgradeRequested =
14999                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15000                    final boolean packageDebuggable =
15001                                (dataOwnerPkg.applicationInfo.flags
15002                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15003                    final boolean downgradePermitted =
15004                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15005                    if (!downgradePermitted) {
15006                        try {
15007                            checkDowngrade(dataOwnerPkg, pkgLite);
15008                        } catch (PackageManagerException e) {
15009                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15010                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15011                        }
15012                    }
15013                }
15014
15015                if (installedPkg != null) {
15016                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15017                        // Check for updated system application.
15018                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15019                            if (onSd) {
15020                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15021                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15022                            }
15023                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15024                        } else {
15025                            if (onSd) {
15026                                // Install flag overrides everything.
15027                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15028                            }
15029                            // If current upgrade specifies particular preference
15030                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15031                                // Application explicitly specified internal.
15032                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15033                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15034                                // App explictly prefers external. Let policy decide
15035                            } else {
15036                                // Prefer previous location
15037                                if (isExternal(installedPkg)) {
15038                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15039                                }
15040                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15041                            }
15042                        }
15043                    } else {
15044                        // Invalid install. Return error code
15045                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15046                    }
15047                }
15048            }
15049            // All the special cases have been taken care of.
15050            // Return result based on recommended install location.
15051            if (onSd) {
15052                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15053            }
15054            return pkgLite.recommendedInstallLocation;
15055        }
15056
15057        /*
15058         * Invoke remote method to get package information and install
15059         * location values. Override install location based on default
15060         * policy if needed and then create install arguments based
15061         * on the install location.
15062         */
15063        public void handleStartCopy() throws RemoteException {
15064            int ret = PackageManager.INSTALL_SUCCEEDED;
15065
15066            // If we're already staged, we've firmly committed to an install location
15067            if (origin.staged) {
15068                if (origin.file != null) {
15069                    installFlags |= PackageManager.INSTALL_INTERNAL;
15070                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15071                } else {
15072                    throw new IllegalStateException("Invalid stage location");
15073                }
15074            }
15075
15076            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15077            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15078            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15079            PackageInfoLite pkgLite = null;
15080
15081            if (onInt && onSd) {
15082                // Check if both bits are set.
15083                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15084                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15085            } else if (onSd && ephemeral) {
15086                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15087                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15088            } else {
15089                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15090                        packageAbiOverride);
15091
15092                if (DEBUG_EPHEMERAL && ephemeral) {
15093                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15094                }
15095
15096                /*
15097                 * If we have too little free space, try to free cache
15098                 * before giving up.
15099                 */
15100                if (!origin.staged && pkgLite.recommendedInstallLocation
15101                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15102                    // TODO: focus freeing disk space on the target device
15103                    final StorageManager storage = StorageManager.from(mContext);
15104                    final long lowThreshold = storage.getStorageLowBytes(
15105                            Environment.getDataDirectory());
15106
15107                    final long sizeBytes = mContainerService.calculateInstalledSize(
15108                            origin.resolvedPath, packageAbiOverride);
15109
15110                    try {
15111                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15112                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15113                                installFlags, packageAbiOverride);
15114                    } catch (InstallerException e) {
15115                        Slog.w(TAG, "Failed to free cache", e);
15116                    }
15117
15118                    /*
15119                     * The cache free must have deleted the file we
15120                     * downloaded to install.
15121                     *
15122                     * TODO: fix the "freeCache" call to not delete
15123                     *       the file we care about.
15124                     */
15125                    if (pkgLite.recommendedInstallLocation
15126                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15127                        pkgLite.recommendedInstallLocation
15128                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15129                    }
15130                }
15131            }
15132
15133            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15134                int loc = pkgLite.recommendedInstallLocation;
15135                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15136                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15137                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15138                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15139                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15140                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15141                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15142                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15143                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15144                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15145                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15146                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15147                } else {
15148                    // Override with defaults if needed.
15149                    loc = installLocationPolicy(pkgLite);
15150                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15151                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15152                    } else if (!onSd && !onInt) {
15153                        // Override install location with flags
15154                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15155                            // Set the flag to install on external media.
15156                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15157                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15158                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15159                            if (DEBUG_EPHEMERAL) {
15160                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15161                            }
15162                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15163                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15164                                    |PackageManager.INSTALL_INTERNAL);
15165                        } else {
15166                            // Make sure the flag for installing on external
15167                            // media is unset
15168                            installFlags |= PackageManager.INSTALL_INTERNAL;
15169                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15170                        }
15171                    }
15172                }
15173            }
15174
15175            final InstallArgs args = createInstallArgs(this);
15176            mArgs = args;
15177
15178            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15179                // TODO: http://b/22976637
15180                // Apps installed for "all" users use the device owner to verify the app
15181                UserHandle verifierUser = getUser();
15182                if (verifierUser == UserHandle.ALL) {
15183                    verifierUser = UserHandle.SYSTEM;
15184                }
15185
15186                /*
15187                 * Determine if we have any installed package verifiers. If we
15188                 * do, then we'll defer to them to verify the packages.
15189                 */
15190                final int requiredUid = mRequiredVerifierPackage == null ? -1
15191                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15192                                verifierUser.getIdentifier());
15193                final int installerUid =
15194                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15195                if (!origin.existing && requiredUid != -1
15196                        && isVerificationEnabled(
15197                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15198                    final Intent verification = new Intent(
15199                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15200                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15201                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15202                            PACKAGE_MIME_TYPE);
15203                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15204
15205                    // Query all live verifiers based on current user state
15206                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15207                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
15208                            false /*allowDynamicSplits*/);
15209
15210                    if (DEBUG_VERIFY) {
15211                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15212                                + verification.toString() + " with " + pkgLite.verifiers.length
15213                                + " optional verifiers");
15214                    }
15215
15216                    final int verificationId = mPendingVerificationToken++;
15217
15218                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15219
15220                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15221                            installerPackageName);
15222
15223                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15224                            installFlags);
15225
15226                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15227                            pkgLite.packageName);
15228
15229                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15230                            pkgLite.versionCode);
15231
15232                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE,
15233                            pkgLite.getLongVersionCode());
15234
15235                    if (verificationInfo != null) {
15236                        if (verificationInfo.originatingUri != null) {
15237                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15238                                    verificationInfo.originatingUri);
15239                        }
15240                        if (verificationInfo.referrer != null) {
15241                            verification.putExtra(Intent.EXTRA_REFERRER,
15242                                    verificationInfo.referrer);
15243                        }
15244                        if (verificationInfo.originatingUid >= 0) {
15245                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15246                                    verificationInfo.originatingUid);
15247                        }
15248                        if (verificationInfo.installerUid >= 0) {
15249                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15250                                    verificationInfo.installerUid);
15251                        }
15252                    }
15253
15254                    final PackageVerificationState verificationState = new PackageVerificationState(
15255                            requiredUid, args);
15256
15257                    mPendingVerification.append(verificationId, verificationState);
15258
15259                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15260                            receivers, verificationState);
15261
15262                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15263                    final long idleDuration = getVerificationTimeout();
15264
15265                    /*
15266                     * If any sufficient verifiers were listed in the package
15267                     * manifest, attempt to ask them.
15268                     */
15269                    if (sufficientVerifiers != null) {
15270                        final int N = sufficientVerifiers.size();
15271                        if (N == 0) {
15272                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15273                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15274                        } else {
15275                            for (int i = 0; i < N; i++) {
15276                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15277                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15278                                        verifierComponent.getPackageName(), idleDuration,
15279                                        verifierUser.getIdentifier(), false, "package verifier");
15280
15281                                final Intent sufficientIntent = new Intent(verification);
15282                                sufficientIntent.setComponent(verifierComponent);
15283                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15284                            }
15285                        }
15286                    }
15287
15288                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15289                            mRequiredVerifierPackage, receivers);
15290                    if (ret == PackageManager.INSTALL_SUCCEEDED
15291                            && mRequiredVerifierPackage != null) {
15292                        Trace.asyncTraceBegin(
15293                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15294                        /*
15295                         * Send the intent to the required verification agent,
15296                         * but only start the verification timeout after the
15297                         * target BroadcastReceivers have run.
15298                         */
15299                        verification.setComponent(requiredVerifierComponent);
15300                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15301                                mRequiredVerifierPackage, idleDuration,
15302                                verifierUser.getIdentifier(), false, "package verifier");
15303                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15304                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15305                                new BroadcastReceiver() {
15306                                    @Override
15307                                    public void onReceive(Context context, Intent intent) {
15308                                        final Message msg = mHandler
15309                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15310                                        msg.arg1 = verificationId;
15311                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15312                                    }
15313                                }, null, 0, null, null);
15314
15315                        /*
15316                         * We don't want the copy to proceed until verification
15317                         * succeeds, so null out this field.
15318                         */
15319                        mArgs = null;
15320                    }
15321                } else {
15322                    /*
15323                     * No package verification is enabled, so immediately start
15324                     * the remote call to initiate copy using temporary file.
15325                     */
15326                    ret = args.copyApk(mContainerService, true);
15327                }
15328            }
15329
15330            mRet = ret;
15331        }
15332
15333        @Override
15334        void handleReturnCode() {
15335            // If mArgs is null, then MCS couldn't be reached. When it
15336            // reconnects, it will try again to install. At that point, this
15337            // will succeed.
15338            if (mArgs != null) {
15339                processPendingInstall(mArgs, mRet);
15340            }
15341        }
15342
15343        @Override
15344        void handleServiceError() {
15345            mArgs = createInstallArgs(this);
15346            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15347        }
15348    }
15349
15350    private InstallArgs createInstallArgs(InstallParams params) {
15351        if (params.move != null) {
15352            return new MoveInstallArgs(params);
15353        } else {
15354            return new FileInstallArgs(params);
15355        }
15356    }
15357
15358    /**
15359     * Create args that describe an existing installed package. Typically used
15360     * when cleaning up old installs, or used as a move source.
15361     */
15362    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15363            String resourcePath, String[] instructionSets) {
15364        return new FileInstallArgs(codePath, resourcePath, instructionSets);
15365    }
15366
15367    static abstract class InstallArgs {
15368        /** @see InstallParams#origin */
15369        final OriginInfo origin;
15370        /** @see InstallParams#move */
15371        final MoveInfo move;
15372
15373        final IPackageInstallObserver2 observer;
15374        // Always refers to PackageManager flags only
15375        final int installFlags;
15376        final String installerPackageName;
15377        final String volumeUuid;
15378        final UserHandle user;
15379        final String abiOverride;
15380        final String[] installGrantPermissions;
15381        /** If non-null, drop an async trace when the install completes */
15382        final String traceMethod;
15383        final int traceCookie;
15384        final PackageParser.SigningDetails signingDetails;
15385        final int installReason;
15386
15387        // The list of instruction sets supported by this app. This is currently
15388        // only used during the rmdex() phase to clean up resources. We can get rid of this
15389        // if we move dex files under the common app path.
15390        /* nullable */ String[] instructionSets;
15391
15392        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15393                int installFlags, String installerPackageName, String volumeUuid,
15394                UserHandle user, String[] instructionSets,
15395                String abiOverride, String[] installGrantPermissions,
15396                String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails,
15397                int installReason) {
15398            this.origin = origin;
15399            this.move = move;
15400            this.installFlags = installFlags;
15401            this.observer = observer;
15402            this.installerPackageName = installerPackageName;
15403            this.volumeUuid = volumeUuid;
15404            this.user = user;
15405            this.instructionSets = instructionSets;
15406            this.abiOverride = abiOverride;
15407            this.installGrantPermissions = installGrantPermissions;
15408            this.traceMethod = traceMethod;
15409            this.traceCookie = traceCookie;
15410            this.signingDetails = signingDetails;
15411            this.installReason = installReason;
15412        }
15413
15414        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15415        abstract int doPreInstall(int status);
15416
15417        /**
15418         * Rename package into final resting place. All paths on the given
15419         * scanned package should be updated to reflect the rename.
15420         */
15421        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15422        abstract int doPostInstall(int status, int uid);
15423
15424        /** @see PackageSettingBase#codePathString */
15425        abstract String getCodePath();
15426        /** @see PackageSettingBase#resourcePathString */
15427        abstract String getResourcePath();
15428
15429        // Need installer lock especially for dex file removal.
15430        abstract void cleanUpResourcesLI();
15431        abstract boolean doPostDeleteLI(boolean delete);
15432
15433        /**
15434         * Called before the source arguments are copied. This is used mostly
15435         * for MoveParams when it needs to read the source file to put it in the
15436         * destination.
15437         */
15438        int doPreCopy() {
15439            return PackageManager.INSTALL_SUCCEEDED;
15440        }
15441
15442        /**
15443         * Called after the source arguments are copied. This is used mostly for
15444         * MoveParams when it needs to read the source file to put it in the
15445         * destination.
15446         */
15447        int doPostCopy(int uid) {
15448            return PackageManager.INSTALL_SUCCEEDED;
15449        }
15450
15451        protected boolean isFwdLocked() {
15452            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15453        }
15454
15455        protected boolean isExternalAsec() {
15456            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15457        }
15458
15459        protected boolean isEphemeral() {
15460            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15461        }
15462
15463        UserHandle getUser() {
15464            return user;
15465        }
15466    }
15467
15468    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15469        if (!allCodePaths.isEmpty()) {
15470            if (instructionSets == null) {
15471                throw new IllegalStateException("instructionSet == null");
15472            }
15473            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15474            for (String codePath : allCodePaths) {
15475                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15476                    try {
15477                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15478                    } catch (InstallerException ignored) {
15479                    }
15480                }
15481            }
15482        }
15483    }
15484
15485    /**
15486     * Logic to handle installation of non-ASEC applications, including copying
15487     * and renaming logic.
15488     */
15489    class FileInstallArgs extends InstallArgs {
15490        private File codeFile;
15491        private File resourceFile;
15492
15493        // Example topology:
15494        // /data/app/com.example/base.apk
15495        // /data/app/com.example/split_foo.apk
15496        // /data/app/com.example/lib/arm/libfoo.so
15497        // /data/app/com.example/lib/arm64/libfoo.so
15498        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15499
15500        /** New install */
15501        FileInstallArgs(InstallParams params) {
15502            super(params.origin, params.move, params.observer, params.installFlags,
15503                    params.installerPackageName, params.volumeUuid,
15504                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15505                    params.grantedRuntimePermissions,
15506                    params.traceMethod, params.traceCookie, params.signingDetails,
15507                    params.installReason);
15508            if (isFwdLocked()) {
15509                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15510            }
15511        }
15512
15513        /** Existing install */
15514        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15515            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15516                    null, null, null, 0, PackageParser.SigningDetails.UNKNOWN,
15517                    PackageManager.INSTALL_REASON_UNKNOWN);
15518            this.codeFile = (codePath != null) ? new File(codePath) : null;
15519            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15520        }
15521
15522        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15523            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15524            try {
15525                return doCopyApk(imcs, temp);
15526            } finally {
15527                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15528            }
15529        }
15530
15531        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15532            if (origin.staged) {
15533                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15534                codeFile = origin.file;
15535                resourceFile = origin.file;
15536                return PackageManager.INSTALL_SUCCEEDED;
15537            }
15538
15539            try {
15540                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15541                final File tempDir =
15542                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15543                codeFile = tempDir;
15544                resourceFile = tempDir;
15545            } catch (IOException e) {
15546                Slog.w(TAG, "Failed to create copy file: " + e);
15547                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15548            }
15549
15550            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15551                @Override
15552                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15553                    if (!FileUtils.isValidExtFilename(name)) {
15554                        throw new IllegalArgumentException("Invalid filename: " + name);
15555                    }
15556                    try {
15557                        final File file = new File(codeFile, name);
15558                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15559                                O_RDWR | O_CREAT, 0644);
15560                        Os.chmod(file.getAbsolutePath(), 0644);
15561                        return new ParcelFileDescriptor(fd);
15562                    } catch (ErrnoException e) {
15563                        throw new RemoteException("Failed to open: " + e.getMessage());
15564                    }
15565                }
15566            };
15567
15568            int ret = PackageManager.INSTALL_SUCCEEDED;
15569            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15570            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15571                Slog.e(TAG, "Failed to copy package");
15572                return ret;
15573            }
15574
15575            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15576            NativeLibraryHelper.Handle handle = null;
15577            try {
15578                handle = NativeLibraryHelper.Handle.create(codeFile);
15579                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15580                        abiOverride);
15581            } catch (IOException e) {
15582                Slog.e(TAG, "Copying native libraries failed", e);
15583                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15584            } finally {
15585                IoUtils.closeQuietly(handle);
15586            }
15587
15588            return ret;
15589        }
15590
15591        int doPreInstall(int status) {
15592            if (status != PackageManager.INSTALL_SUCCEEDED) {
15593                cleanUp();
15594            }
15595            return status;
15596        }
15597
15598        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15599            if (status != PackageManager.INSTALL_SUCCEEDED) {
15600                cleanUp();
15601                return false;
15602            }
15603
15604            final File targetDir = codeFile.getParentFile();
15605            final File beforeCodeFile = codeFile;
15606            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15607
15608            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15609            try {
15610                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15611            } catch (ErrnoException e) {
15612                Slog.w(TAG, "Failed to rename", e);
15613                return false;
15614            }
15615
15616            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15617                Slog.w(TAG, "Failed to restorecon");
15618                return false;
15619            }
15620
15621            // Reflect the rename internally
15622            codeFile = afterCodeFile;
15623            resourceFile = afterCodeFile;
15624
15625            // Reflect the rename in scanned details
15626            try {
15627                pkg.setCodePath(afterCodeFile.getCanonicalPath());
15628            } catch (IOException e) {
15629                Slog.e(TAG, "Failed to get path: " + afterCodeFile, e);
15630                return false;
15631            }
15632            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15633                    afterCodeFile, pkg.baseCodePath));
15634            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15635                    afterCodeFile, pkg.splitCodePaths));
15636
15637            // Reflect the rename in app info
15638            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15639            pkg.setApplicationInfoCodePath(pkg.codePath);
15640            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15641            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15642            pkg.setApplicationInfoResourcePath(pkg.codePath);
15643            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15644            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15645
15646            return true;
15647        }
15648
15649        int doPostInstall(int status, int uid) {
15650            if (status != PackageManager.INSTALL_SUCCEEDED) {
15651                cleanUp();
15652            }
15653            return status;
15654        }
15655
15656        @Override
15657        String getCodePath() {
15658            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15659        }
15660
15661        @Override
15662        String getResourcePath() {
15663            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15664        }
15665
15666        private boolean cleanUp() {
15667            if (codeFile == null || !codeFile.exists()) {
15668                return false;
15669            }
15670
15671            removeCodePathLI(codeFile);
15672
15673            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15674                resourceFile.delete();
15675            }
15676
15677            return true;
15678        }
15679
15680        void cleanUpResourcesLI() {
15681            // Try enumerating all code paths before deleting
15682            List<String> allCodePaths = Collections.EMPTY_LIST;
15683            if (codeFile != null && codeFile.exists()) {
15684                try {
15685                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15686                    allCodePaths = pkg.getAllCodePaths();
15687                } catch (PackageParserException e) {
15688                    // Ignored; we tried our best
15689                }
15690            }
15691
15692            cleanUp();
15693            removeDexFiles(allCodePaths, instructionSets);
15694        }
15695
15696        boolean doPostDeleteLI(boolean delete) {
15697            // XXX err, shouldn't we respect the delete flag?
15698            cleanUpResourcesLI();
15699            return true;
15700        }
15701    }
15702
15703    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15704            PackageManagerException {
15705        if (copyRet < 0) {
15706            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15707                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15708                throw new PackageManagerException(copyRet, message);
15709            }
15710        }
15711    }
15712
15713    /**
15714     * Extract the StorageManagerService "container ID" from the full code path of an
15715     * .apk.
15716     */
15717    static String cidFromCodePath(String fullCodePath) {
15718        int eidx = fullCodePath.lastIndexOf("/");
15719        String subStr1 = fullCodePath.substring(0, eidx);
15720        int sidx = subStr1.lastIndexOf("/");
15721        return subStr1.substring(sidx+1, eidx);
15722    }
15723
15724    /**
15725     * Logic to handle movement of existing installed applications.
15726     */
15727    class MoveInstallArgs extends InstallArgs {
15728        private File codeFile;
15729        private File resourceFile;
15730
15731        /** New install */
15732        MoveInstallArgs(InstallParams params) {
15733            super(params.origin, params.move, params.observer, params.installFlags,
15734                    params.installerPackageName, params.volumeUuid,
15735                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15736                    params.grantedRuntimePermissions,
15737                    params.traceMethod, params.traceCookie, params.signingDetails,
15738                    params.installReason);
15739        }
15740
15741        int copyApk(IMediaContainerService imcs, boolean temp) {
15742            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15743                    + move.fromUuid + " to " + move.toUuid);
15744            synchronized (mInstaller) {
15745                try {
15746                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15747                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15748                } catch (InstallerException e) {
15749                    Slog.w(TAG, "Failed to move app", e);
15750                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15751                }
15752            }
15753
15754            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15755            resourceFile = codeFile;
15756            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15757
15758            return PackageManager.INSTALL_SUCCEEDED;
15759        }
15760
15761        int doPreInstall(int status) {
15762            if (status != PackageManager.INSTALL_SUCCEEDED) {
15763                cleanUp(move.toUuid);
15764            }
15765            return status;
15766        }
15767
15768        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15769            if (status != PackageManager.INSTALL_SUCCEEDED) {
15770                cleanUp(move.toUuid);
15771                return false;
15772            }
15773
15774            // Reflect the move in app info
15775            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15776            pkg.setApplicationInfoCodePath(pkg.codePath);
15777            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15778            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15779            pkg.setApplicationInfoResourcePath(pkg.codePath);
15780            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15781            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15782
15783            return true;
15784        }
15785
15786        int doPostInstall(int status, int uid) {
15787            if (status == PackageManager.INSTALL_SUCCEEDED) {
15788                cleanUp(move.fromUuid);
15789            } else {
15790                cleanUp(move.toUuid);
15791            }
15792            return status;
15793        }
15794
15795        @Override
15796        String getCodePath() {
15797            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15798        }
15799
15800        @Override
15801        String getResourcePath() {
15802            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15803        }
15804
15805        private boolean cleanUp(String volumeUuid) {
15806            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15807                    move.dataAppName);
15808            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15809            final int[] userIds = sUserManager.getUserIds();
15810            synchronized (mInstallLock) {
15811                // Clean up both app data and code
15812                // All package moves are frozen until finished
15813                for (int userId : userIds) {
15814                    try {
15815                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15816                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15817                    } catch (InstallerException e) {
15818                        Slog.w(TAG, String.valueOf(e));
15819                    }
15820                }
15821                removeCodePathLI(codeFile);
15822            }
15823            return true;
15824        }
15825
15826        void cleanUpResourcesLI() {
15827            throw new UnsupportedOperationException();
15828        }
15829
15830        boolean doPostDeleteLI(boolean delete) {
15831            throw new UnsupportedOperationException();
15832        }
15833    }
15834
15835    static String getAsecPackageName(String packageCid) {
15836        int idx = packageCid.lastIndexOf("-");
15837        if (idx == -1) {
15838            return packageCid;
15839        }
15840        return packageCid.substring(0, idx);
15841    }
15842
15843    // Utility method used to create code paths based on package name and available index.
15844    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15845        String idxStr = "";
15846        int idx = 1;
15847        // Fall back to default value of idx=1 if prefix is not
15848        // part of oldCodePath
15849        if (oldCodePath != null) {
15850            String subStr = oldCodePath;
15851            // Drop the suffix right away
15852            if (suffix != null && subStr.endsWith(suffix)) {
15853                subStr = subStr.substring(0, subStr.length() - suffix.length());
15854            }
15855            // If oldCodePath already contains prefix find out the
15856            // ending index to either increment or decrement.
15857            int sidx = subStr.lastIndexOf(prefix);
15858            if (sidx != -1) {
15859                subStr = subStr.substring(sidx + prefix.length());
15860                if (subStr != null) {
15861                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15862                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15863                    }
15864                    try {
15865                        idx = Integer.parseInt(subStr);
15866                        if (idx <= 1) {
15867                            idx++;
15868                        } else {
15869                            idx--;
15870                        }
15871                    } catch(NumberFormatException e) {
15872                    }
15873                }
15874            }
15875        }
15876        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15877        return prefix + idxStr;
15878    }
15879
15880    private File getNextCodePath(File targetDir, String packageName) {
15881        File result;
15882        SecureRandom random = new SecureRandom();
15883        byte[] bytes = new byte[16];
15884        do {
15885            random.nextBytes(bytes);
15886            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15887            result = new File(targetDir, packageName + "-" + suffix);
15888        } while (result.exists());
15889        return result;
15890    }
15891
15892    // Utility method that returns the relative package path with respect
15893    // to the installation directory. Like say for /data/data/com.test-1.apk
15894    // string com.test-1 is returned.
15895    static String deriveCodePathName(String codePath) {
15896        if (codePath == null) {
15897            return null;
15898        }
15899        final File codeFile = new File(codePath);
15900        final String name = codeFile.getName();
15901        if (codeFile.isDirectory()) {
15902            return name;
15903        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15904            final int lastDot = name.lastIndexOf('.');
15905            return name.substring(0, lastDot);
15906        } else {
15907            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15908            return null;
15909        }
15910    }
15911
15912    static class PackageInstalledInfo {
15913        String name;
15914        int uid;
15915        // The set of users that originally had this package installed.
15916        int[] origUsers;
15917        // The set of users that now have this package installed.
15918        int[] newUsers;
15919        PackageParser.Package pkg;
15920        int returnCode;
15921        String returnMsg;
15922        String installerPackageName;
15923        PackageRemovedInfo removedInfo;
15924        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15925
15926        public void setError(int code, String msg) {
15927            setReturnCode(code);
15928            setReturnMessage(msg);
15929            Slog.w(TAG, msg);
15930        }
15931
15932        public void setError(String msg, PackageParserException e) {
15933            setReturnCode(e.error);
15934            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15935            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15936            for (int i = 0; i < childCount; i++) {
15937                addedChildPackages.valueAt(i).setError(msg, e);
15938            }
15939            Slog.w(TAG, msg, e);
15940        }
15941
15942        public void setError(String msg, PackageManagerException e) {
15943            returnCode = e.error;
15944            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15945            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15946            for (int i = 0; i < childCount; i++) {
15947                addedChildPackages.valueAt(i).setError(msg, e);
15948            }
15949            Slog.w(TAG, msg, e);
15950        }
15951
15952        public void setReturnCode(int returnCode) {
15953            this.returnCode = returnCode;
15954            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15955            for (int i = 0; i < childCount; i++) {
15956                addedChildPackages.valueAt(i).returnCode = returnCode;
15957            }
15958        }
15959
15960        private void setReturnMessage(String returnMsg) {
15961            this.returnMsg = returnMsg;
15962            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15963            for (int i = 0; i < childCount; i++) {
15964                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15965            }
15966        }
15967
15968        // In some error cases we want to convey more info back to the observer
15969        String origPackage;
15970        String origPermission;
15971    }
15972
15973    /*
15974     * Install a non-existing package.
15975     */
15976    private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
15977            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
15978            String volumeUuid, PackageInstalledInfo res, int installReason) {
15979        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15980
15981        // Remember this for later, in case we need to rollback this install
15982        String pkgName = pkg.packageName;
15983
15984        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15985
15986        synchronized(mPackages) {
15987            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15988            if (renamedPackage != null) {
15989                // A package with the same name is already installed, though
15990                // it has been renamed to an older name.  The package we
15991                // are trying to install should be installed as an update to
15992                // the existing one, but that has not been requested, so bail.
15993                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15994                        + " without first uninstalling package running as "
15995                        + renamedPackage);
15996                return;
15997            }
15998            if (mPackages.containsKey(pkgName)) {
15999                // Don't allow installation over an existing package with the same name.
16000                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16001                        + " without first uninstalling.");
16002                return;
16003            }
16004        }
16005
16006        try {
16007            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
16008                    System.currentTimeMillis(), user);
16009
16010            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16011
16012            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16013                prepareAppDataAfterInstallLIF(newPackage);
16014
16015            } else {
16016                // Remove package from internal structures, but keep around any
16017                // data that might have already existed
16018                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16019                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16020            }
16021        } catch (PackageManagerException e) {
16022            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16023        }
16024
16025        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16026    }
16027
16028    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16029        try (DigestInputStream digestStream =
16030                new DigestInputStream(new FileInputStream(file), digest)) {
16031            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16032        }
16033    }
16034
16035    private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
16036            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
16037            PackageInstalledInfo res, int installReason) {
16038        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16039
16040        final PackageParser.Package oldPackage;
16041        final PackageSetting ps;
16042        final String pkgName = pkg.packageName;
16043        final int[] allUsers;
16044        final int[] installedUsers;
16045
16046        synchronized(mPackages) {
16047            oldPackage = mPackages.get(pkgName);
16048            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
16049
16050            // don't allow upgrade to target a release SDK from a pre-release SDK
16051            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
16052                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16053            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
16054                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16055            if (oldTargetsPreRelease
16056                    && !newTargetsPreRelease
16057                    && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16058                Slog.w(TAG, "Can't install package targeting released sdk");
16059                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16060                return;
16061            }
16062
16063            ps = mSettings.mPackages.get(pkgName);
16064
16065            // verify signatures are valid
16066            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16067            if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) {
16068                if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) {
16069                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16070                            "New package not signed by keys specified by upgrade-keysets: "
16071                                    + pkgName);
16072                    return;
16073                }
16074            } else {
16075                // default to original signature matching
16076                if (compareSignatures(oldPackage.mSigningDetails.signatures,
16077                        pkg.mSigningDetails.signatures)
16078                        != PackageManager.SIGNATURE_MATCH) {
16079                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16080                            "New package has a different signature: " + pkgName);
16081                    return;
16082                }
16083            }
16084
16085            // don't allow a system upgrade unless the upgrade hash matches
16086            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) {
16087                byte[] digestBytes = null;
16088                try {
16089                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16090                    updateDigest(digest, new File(pkg.baseCodePath));
16091                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16092                        for (String path : pkg.splitCodePaths) {
16093                            updateDigest(digest, new File(path));
16094                        }
16095                    }
16096                    digestBytes = digest.digest();
16097                } catch (NoSuchAlgorithmException | IOException e) {
16098                    res.setError(INSTALL_FAILED_INVALID_APK,
16099                            "Could not compute hash: " + pkgName);
16100                    return;
16101                }
16102                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16103                    res.setError(INSTALL_FAILED_INVALID_APK,
16104                            "New package fails restrict-update check: " + pkgName);
16105                    return;
16106                }
16107                // retain upgrade restriction
16108                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16109            }
16110
16111            // Check for shared user id changes
16112            String invalidPackageName =
16113                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16114            if (invalidPackageName != null) {
16115                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16116                        "Package " + invalidPackageName + " tried to change user "
16117                                + oldPackage.mSharedUserId);
16118                return;
16119            }
16120
16121            // check if the new package supports all of the abis which the old package supports
16122            boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null;
16123            boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null;
16124            if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) {
16125                res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16126                        "Update to package " + pkgName + " doesn't support multi arch");
16127                return;
16128            }
16129
16130            // In case of rollback, remember per-user/profile install state
16131            allUsers = sUserManager.getUserIds();
16132            installedUsers = ps.queryInstalledUsers(allUsers, true);
16133
16134            // don't allow an upgrade from full to ephemeral
16135            if (isInstantApp) {
16136                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16137                    for (int currentUser : allUsers) {
16138                        if (!ps.getInstantApp(currentUser)) {
16139                            // can't downgrade from full to instant
16140                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16141                                    + " for user: " + currentUser);
16142                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16143                            return;
16144                        }
16145                    }
16146                } else if (!ps.getInstantApp(user.getIdentifier())) {
16147                    // can't downgrade from full to instant
16148                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16149                            + " for user: " + user.getIdentifier());
16150                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16151                    return;
16152                }
16153            }
16154        }
16155
16156        // Update what is removed
16157        res.removedInfo = new PackageRemovedInfo(this);
16158        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16159        res.removedInfo.removedPackage = oldPackage.packageName;
16160        res.removedInfo.installerPackageName = ps.installerPackageName;
16161        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16162        res.removedInfo.isUpdate = true;
16163        res.removedInfo.origUsers = installedUsers;
16164        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16165        for (int i = 0; i < installedUsers.length; i++) {
16166            final int userId = installedUsers[i];
16167            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16168        }
16169
16170        final int childCount = (oldPackage.childPackages != null)
16171                ? oldPackage.childPackages.size() : 0;
16172        for (int i = 0; i < childCount; i++) {
16173            boolean childPackageUpdated = false;
16174            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16175            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16176            if (res.addedChildPackages != null) {
16177                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16178                if (childRes != null) {
16179                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16180                    childRes.removedInfo.removedPackage = childPkg.packageName;
16181                    if (childPs != null) {
16182                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16183                    }
16184                    childRes.removedInfo.isUpdate = true;
16185                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16186                    childPackageUpdated = true;
16187                }
16188            }
16189            if (!childPackageUpdated) {
16190                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16191                childRemovedRes.removedPackage = childPkg.packageName;
16192                if (childPs != null) {
16193                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16194                }
16195                childRemovedRes.isUpdate = false;
16196                childRemovedRes.dataRemoved = true;
16197                synchronized (mPackages) {
16198                    if (childPs != null) {
16199                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16200                    }
16201                }
16202                if (res.removedInfo.removedChildPackages == null) {
16203                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16204                }
16205                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16206            }
16207        }
16208
16209        boolean sysPkg = (isSystemApp(oldPackage));
16210        if (sysPkg) {
16211            // Set the system/privileged/oem/vendor/product flags as needed
16212            final boolean privileged =
16213                    (oldPackage.applicationInfo.privateFlags
16214                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16215            final boolean oem =
16216                    (oldPackage.applicationInfo.privateFlags
16217                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
16218            final boolean vendor =
16219                    (oldPackage.applicationInfo.privateFlags
16220                            & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
16221            final boolean product =
16222                    (oldPackage.applicationInfo.privateFlags
16223                            & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
16224            final @ParseFlags int systemParseFlags = parseFlags;
16225            final @ScanFlags int systemScanFlags = scanFlags
16226                    | SCAN_AS_SYSTEM
16227                    | (privileged ? SCAN_AS_PRIVILEGED : 0)
16228                    | (oem ? SCAN_AS_OEM : 0)
16229                    | (vendor ? SCAN_AS_VENDOR : 0)
16230                    | (product ? SCAN_AS_PRODUCT : 0);
16231
16232            replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags,
16233                    user, allUsers, installerPackageName, res, installReason);
16234        } else {
16235            replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags,
16236                    user, allUsers, installerPackageName, res, installReason);
16237        }
16238    }
16239
16240    @Override
16241    public List<String> getPreviousCodePaths(String packageName) {
16242        final int callingUid = Binder.getCallingUid();
16243        final List<String> result = new ArrayList<>();
16244        if (getInstantAppPackageName(callingUid) != null) {
16245            return result;
16246        }
16247        final PackageSetting ps = mSettings.mPackages.get(packageName);
16248        if (ps != null
16249                && ps.oldCodePaths != null
16250                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
16251            result.addAll(ps.oldCodePaths);
16252        }
16253        return result;
16254    }
16255
16256    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16257            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16258            final @ScanFlags int scanFlags, UserHandle user, int[] allUsers,
16259            String installerPackageName, PackageInstalledInfo res, int installReason) {
16260        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16261                + deletedPackage);
16262
16263        String pkgName = deletedPackage.packageName;
16264        boolean deletedPkg = true;
16265        boolean addedPkg = false;
16266        boolean updatedSettings = false;
16267        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16268        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16269                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16270
16271        final long origUpdateTime = (pkg.mExtras != null)
16272                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16273
16274        // First delete the existing package while retaining the data directory
16275        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16276                res.removedInfo, true, pkg)) {
16277            // If the existing package wasn't successfully deleted
16278            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16279            deletedPkg = false;
16280        } else {
16281            // Successfully deleted the old package; proceed with replace.
16282
16283            // If deleted package lived in a container, give users a chance to
16284            // relinquish resources before killing.
16285            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16286                if (DEBUG_INSTALL) {
16287                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16288                }
16289                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16290                final ArrayList<String> pkgList = new ArrayList<String>(1);
16291                pkgList.add(deletedPackage.applicationInfo.packageName);
16292                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16293            }
16294
16295            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16296                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16297
16298            try {
16299                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
16300                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16301                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16302                        installReason);
16303
16304                // Update the in-memory copy of the previous code paths.
16305                PackageSetting ps = mSettings.mPackages.get(pkgName);
16306                if (!killApp) {
16307                    if (ps.oldCodePaths == null) {
16308                        ps.oldCodePaths = new ArraySet<>();
16309                    }
16310                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16311                    if (deletedPackage.splitCodePaths != null) {
16312                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16313                    }
16314                } else {
16315                    ps.oldCodePaths = null;
16316                }
16317                if (ps.childPackageNames != null) {
16318                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16319                        final String childPkgName = ps.childPackageNames.get(i);
16320                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16321                        childPs.oldCodePaths = ps.oldCodePaths;
16322                    }
16323                }
16324                // set instant app status, but, only if it's explicitly specified
16325                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16326                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16327                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16328                prepareAppDataAfterInstallLIF(newPackage);
16329                addedPkg = true;
16330                mDexManager.notifyPackageUpdated(newPackage.packageName,
16331                        newPackage.baseCodePath, newPackage.splitCodePaths);
16332            } catch (PackageManagerException e) {
16333                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16334            }
16335        }
16336
16337        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16338            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16339
16340            // Revert all internal state mutations and added folders for the failed install
16341            if (addedPkg) {
16342                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16343                        res.removedInfo, true, null);
16344            }
16345
16346            // Restore the old package
16347            if (deletedPkg) {
16348                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16349                File restoreFile = new File(deletedPackage.codePath);
16350                // Parse old package
16351                boolean oldExternal = isExternal(deletedPackage);
16352                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16353                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16354                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16355                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16356                try {
16357                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16358                            null);
16359                } catch (PackageManagerException e) {
16360                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16361                            + e.getMessage());
16362                    return;
16363                }
16364
16365                synchronized (mPackages) {
16366                    // Ensure the installer package name up to date
16367                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16368
16369                    // Update permissions for restored package
16370                    mPermissionManager.updatePermissions(
16371                            deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16372                            mPermissionCallback);
16373
16374                    mSettings.writeLPr();
16375                }
16376
16377                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16378            }
16379        } else {
16380            synchronized (mPackages) {
16381                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16382                if (ps != null) {
16383                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16384                    if (res.removedInfo.removedChildPackages != null) {
16385                        final int childCount = res.removedInfo.removedChildPackages.size();
16386                        // Iterate in reverse as we may modify the collection
16387                        for (int i = childCount - 1; i >= 0; i--) {
16388                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16389                            if (res.addedChildPackages.containsKey(childPackageName)) {
16390                                res.removedInfo.removedChildPackages.removeAt(i);
16391                            } else {
16392                                PackageRemovedInfo childInfo = res.removedInfo
16393                                        .removedChildPackages.valueAt(i);
16394                                childInfo.removedForAllUsers = mPackages.get(
16395                                        childInfo.removedPackage) == null;
16396                            }
16397                        }
16398                    }
16399                }
16400            }
16401        }
16402    }
16403
16404    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16405            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16406            final @ScanFlags int scanFlags, UserHandle user,
16407            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16408            int installReason) {
16409        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16410                + ", old=" + deletedPackage);
16411
16412        final boolean disabledSystem;
16413
16414        // Remove existing system package
16415        removePackageLI(deletedPackage, true);
16416
16417        synchronized (mPackages) {
16418            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16419        }
16420        if (!disabledSystem) {
16421            // We didn't need to disable the .apk as a current system package,
16422            // which means we are replacing another update that is already
16423            // installed.  We need to make sure to delete the older one's .apk.
16424            res.removedInfo.args = createInstallArgsForExisting(0,
16425                    deletedPackage.applicationInfo.getCodePath(),
16426                    deletedPackage.applicationInfo.getResourcePath(),
16427                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16428        } else {
16429            res.removedInfo.args = null;
16430        }
16431
16432        // Successfully disabled the old package. Now proceed with re-installation
16433        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16434                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16435
16436        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16437        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16438                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16439
16440        PackageParser.Package newPackage = null;
16441        try {
16442            // Add the package to the internal data structures
16443            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
16444
16445            // Set the update and install times
16446            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16447            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16448                    System.currentTimeMillis());
16449
16450            // Update the package dynamic state if succeeded
16451            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16452                // Now that the install succeeded make sure we remove data
16453                // directories for any child package the update removed.
16454                final int deletedChildCount = (deletedPackage.childPackages != null)
16455                        ? deletedPackage.childPackages.size() : 0;
16456                final int newChildCount = (newPackage.childPackages != null)
16457                        ? newPackage.childPackages.size() : 0;
16458                for (int i = 0; i < deletedChildCount; i++) {
16459                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16460                    boolean childPackageDeleted = true;
16461                    for (int j = 0; j < newChildCount; j++) {
16462                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16463                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16464                            childPackageDeleted = false;
16465                            break;
16466                        }
16467                    }
16468                    if (childPackageDeleted) {
16469                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16470                                deletedChildPkg.packageName);
16471                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16472                            PackageRemovedInfo removedChildRes = res.removedInfo
16473                                    .removedChildPackages.get(deletedChildPkg.packageName);
16474                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16475                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16476                        }
16477                    }
16478                }
16479
16480                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16481                        installReason);
16482                prepareAppDataAfterInstallLIF(newPackage);
16483
16484                mDexManager.notifyPackageUpdated(newPackage.packageName,
16485                            newPackage.baseCodePath, newPackage.splitCodePaths);
16486            }
16487        } catch (PackageManagerException e) {
16488            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16489            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16490        }
16491
16492        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16493            // Re installation failed. Restore old information
16494            // Remove new pkg information
16495            if (newPackage != null) {
16496                removeInstalledPackageLI(newPackage, true);
16497            }
16498            // Add back the old system package
16499            try {
16500                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16501            } catch (PackageManagerException e) {
16502                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16503            }
16504
16505            synchronized (mPackages) {
16506                if (disabledSystem) {
16507                    enableSystemPackageLPw(deletedPackage);
16508                }
16509
16510                // Ensure the installer package name up to date
16511                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16512
16513                // Update permissions for restored package
16514                mPermissionManager.updatePermissions(
16515                        deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16516                        mPermissionCallback);
16517
16518                mSettings.writeLPr();
16519            }
16520
16521            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16522                    + " after failed upgrade");
16523        }
16524    }
16525
16526    /**
16527     * Checks whether the parent or any of the child packages have a change shared
16528     * user. For a package to be a valid update the shred users of the parent and
16529     * the children should match. We may later support changing child shared users.
16530     * @param oldPkg The updated package.
16531     * @param newPkg The update package.
16532     * @return The shared user that change between the versions.
16533     */
16534    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16535            PackageParser.Package newPkg) {
16536        // Check parent shared user
16537        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16538            return newPkg.packageName;
16539        }
16540        // Check child shared users
16541        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16542        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16543        for (int i = 0; i < newChildCount; i++) {
16544            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16545            // If this child was present, did it have the same shared user?
16546            for (int j = 0; j < oldChildCount; j++) {
16547                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16548                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16549                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16550                    return newChildPkg.packageName;
16551                }
16552            }
16553        }
16554        return null;
16555    }
16556
16557    private void removeNativeBinariesLI(PackageSetting ps) {
16558        // Remove the lib path for the parent package
16559        if (ps != null) {
16560            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16561            // Remove the lib path for the child packages
16562            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16563            for (int i = 0; i < childCount; i++) {
16564                PackageSetting childPs = null;
16565                synchronized (mPackages) {
16566                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16567                }
16568                if (childPs != null) {
16569                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16570                            .legacyNativeLibraryPathString);
16571                }
16572            }
16573        }
16574    }
16575
16576    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16577        // Enable the parent package
16578        mSettings.enableSystemPackageLPw(pkg.packageName);
16579        // Enable the child packages
16580        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16581        for (int i = 0; i < childCount; i++) {
16582            PackageParser.Package childPkg = pkg.childPackages.get(i);
16583            mSettings.enableSystemPackageLPw(childPkg.packageName);
16584        }
16585    }
16586
16587    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16588            PackageParser.Package newPkg) {
16589        // Disable the parent package (parent always replaced)
16590        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16591        // Disable the child packages
16592        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16593        for (int i = 0; i < childCount; i++) {
16594            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16595            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16596            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16597        }
16598        return disabled;
16599    }
16600
16601    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16602            String installerPackageName) {
16603        // Enable the parent package
16604        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16605        // Enable the child packages
16606        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16607        for (int i = 0; i < childCount; i++) {
16608            PackageParser.Package childPkg = pkg.childPackages.get(i);
16609            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16610        }
16611    }
16612
16613    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16614            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16615        // Update the parent package setting
16616        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16617                res, user, installReason);
16618        // Update the child packages setting
16619        final int childCount = (newPackage.childPackages != null)
16620                ? newPackage.childPackages.size() : 0;
16621        for (int i = 0; i < childCount; i++) {
16622            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16623            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16624            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16625                    childRes.origUsers, childRes, user, installReason);
16626        }
16627    }
16628
16629    private void updateSettingsInternalLI(PackageParser.Package pkg,
16630            String installerPackageName, int[] allUsers, int[] installedForUsers,
16631            PackageInstalledInfo res, UserHandle user, int installReason) {
16632        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16633
16634        String pkgName = pkg.packageName;
16635        synchronized (mPackages) {
16636            //write settings. the installStatus will be incomplete at this stage.
16637            //note that the new package setting would have already been
16638            //added to mPackages. It hasn't been persisted yet.
16639            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16640            // TODO: Remove this write? It's also written at the end of this method
16641            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16642            mSettings.writeLPr();
16643            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16644        }
16645
16646        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath);
16647        synchronized (mPackages) {
16648// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions
16649            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
16650                    mPermissionCallback);
16651            // For system-bundled packages, we assume that installing an upgraded version
16652            // of the package implies that the user actually wants to run that new code,
16653            // so we enable the package.
16654            PackageSetting ps = mSettings.mPackages.get(pkgName);
16655            final int userId = user.getIdentifier();
16656            if (ps != null) {
16657                if (isSystemApp(pkg)) {
16658                    if (DEBUG_INSTALL) {
16659                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16660                    }
16661                    // Enable system package for requested users
16662                    if (res.origUsers != null) {
16663                        for (int origUserId : res.origUsers) {
16664                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16665                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16666                                        origUserId, installerPackageName);
16667                            }
16668                        }
16669                    }
16670                    // Also convey the prior install/uninstall state
16671                    if (allUsers != null && installedForUsers != null) {
16672                        for (int currentUserId : allUsers) {
16673                            final boolean installed = ArrayUtils.contains(
16674                                    installedForUsers, currentUserId);
16675                            if (DEBUG_INSTALL) {
16676                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16677                            }
16678                            ps.setInstalled(installed, currentUserId);
16679                        }
16680                        // these install state changes will be persisted in the
16681                        // upcoming call to mSettings.writeLPr().
16682                    }
16683                }
16684                // It's implied that when a user requests installation, they want the app to be
16685                // installed and enabled.
16686                if (userId != UserHandle.USER_ALL) {
16687                    ps.setInstalled(true, userId);
16688                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16689                }
16690
16691                // When replacing an existing package, preserve the original install reason for all
16692                // users that had the package installed before.
16693                final Set<Integer> previousUserIds = new ArraySet<>();
16694                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16695                    final int installReasonCount = res.removedInfo.installReasons.size();
16696                    for (int i = 0; i < installReasonCount; i++) {
16697                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16698                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16699                        ps.setInstallReason(previousInstallReason, previousUserId);
16700                        previousUserIds.add(previousUserId);
16701                    }
16702                }
16703
16704                // Set install reason for users that are having the package newly installed.
16705                if (userId == UserHandle.USER_ALL) {
16706                    for (int currentUserId : sUserManager.getUserIds()) {
16707                        if (!previousUserIds.contains(currentUserId)) {
16708                            ps.setInstallReason(installReason, currentUserId);
16709                        }
16710                    }
16711                } else if (!previousUserIds.contains(userId)) {
16712                    ps.setInstallReason(installReason, userId);
16713                }
16714                mSettings.writeKernelMappingLPr(ps);
16715            }
16716            res.name = pkgName;
16717            res.uid = pkg.applicationInfo.uid;
16718            res.pkg = pkg;
16719            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16720            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16721            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16722            //to update install status
16723            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16724            mSettings.writeLPr();
16725            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16726        }
16727
16728        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16729    }
16730
16731    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16732        try {
16733            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16734            installPackageLI(args, res);
16735        } finally {
16736            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16737        }
16738    }
16739
16740    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16741        final int installFlags = args.installFlags;
16742        final String installerPackageName = args.installerPackageName;
16743        final String volumeUuid = args.volumeUuid;
16744        final File tmpPackageFile = new File(args.getCodePath());
16745        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16746        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16747                || (args.volumeUuid != null));
16748        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16749        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16750        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16751        final boolean virtualPreload =
16752                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
16753        boolean replace = false;
16754        @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16755        if (args.move != null) {
16756            // moving a complete application; perform an initial scan on the new install location
16757            scanFlags |= SCAN_INITIAL;
16758        }
16759        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16760            scanFlags |= SCAN_DONT_KILL_APP;
16761        }
16762        if (instantApp) {
16763            scanFlags |= SCAN_AS_INSTANT_APP;
16764        }
16765        if (fullApp) {
16766            scanFlags |= SCAN_AS_FULL_APP;
16767        }
16768        if (virtualPreload) {
16769            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
16770        }
16771
16772        // Result object to be returned
16773        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16774        res.installerPackageName = installerPackageName;
16775
16776        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16777
16778        // Sanity check
16779        if (instantApp && (forwardLocked || onExternal)) {
16780            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16781                    + " external=" + onExternal);
16782            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16783            return;
16784        }
16785
16786        // Retrieve PackageSettings and parse package
16787        @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16788                | PackageParser.PARSE_ENFORCE_CODE
16789                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16790                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16791                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16792        PackageParser pp = new PackageParser();
16793        pp.setSeparateProcesses(mSeparateProcesses);
16794        pp.setDisplayMetrics(mMetrics);
16795        pp.setCallback(mPackageParserCallback);
16796
16797        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16798        final PackageParser.Package pkg;
16799        try {
16800            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16801            DexMetadataHelper.validatePackageDexMetadata(pkg);
16802        } catch (PackageParserException e) {
16803            res.setError("Failed parse during installPackageLI", e);
16804            return;
16805        } finally {
16806            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16807        }
16808
16809        // Instant apps have several additional install-time checks.
16810        if (instantApp) {
16811            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
16812                Slog.w(TAG,
16813                        "Instant app package " + pkg.packageName + " does not target at least O");
16814                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16815                        "Instant app package must target at least O");
16816                return;
16817            }
16818            if (pkg.applicationInfo.targetSandboxVersion != 2) {
16819                Slog.w(TAG, "Instant app package " + pkg.packageName
16820                        + " does not target targetSandboxVersion 2");
16821                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16822                        "Instant app package must use targetSandboxVersion 2");
16823                return;
16824            }
16825            if (pkg.mSharedUserId != null) {
16826                Slog.w(TAG, "Instant app package " + pkg.packageName
16827                        + " may not declare sharedUserId.");
16828                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16829                        "Instant app package may not declare a sharedUserId");
16830                return;
16831            }
16832        }
16833
16834        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16835            // Static shared libraries have synthetic package names
16836            renameStaticSharedLibraryPackage(pkg);
16837
16838            // No static shared libs on external storage
16839            if (onExternal) {
16840                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16841                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16842                        "Packages declaring static-shared libs cannot be updated");
16843                return;
16844            }
16845        }
16846
16847        // If we are installing a clustered package add results for the children
16848        if (pkg.childPackages != null) {
16849            synchronized (mPackages) {
16850                final int childCount = pkg.childPackages.size();
16851                for (int i = 0; i < childCount; i++) {
16852                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16853                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16854                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16855                    childRes.pkg = childPkg;
16856                    childRes.name = childPkg.packageName;
16857                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16858                    if (childPs != null) {
16859                        childRes.origUsers = childPs.queryInstalledUsers(
16860                                sUserManager.getUserIds(), true);
16861                    }
16862                    if ((mPackages.containsKey(childPkg.packageName))) {
16863                        childRes.removedInfo = new PackageRemovedInfo(this);
16864                        childRes.removedInfo.removedPackage = childPkg.packageName;
16865                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16866                    }
16867                    if (res.addedChildPackages == null) {
16868                        res.addedChildPackages = new ArrayMap<>();
16869                    }
16870                    res.addedChildPackages.put(childPkg.packageName, childRes);
16871                }
16872            }
16873        }
16874
16875        // If package doesn't declare API override, mark that we have an install
16876        // time CPU ABI override.
16877        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16878            pkg.cpuAbiOverride = args.abiOverride;
16879        }
16880
16881        String pkgName = res.name = pkg.packageName;
16882        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16883            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16884                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16885                return;
16886            }
16887        }
16888
16889        try {
16890            // either use what we've been given or parse directly from the APK
16891            if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) {
16892                pkg.setSigningDetails(args.signingDetails);
16893            } else {
16894                PackageParser.collectCertificates(pkg, false /* skipVerify */);
16895            }
16896        } catch (PackageParserException e) {
16897            res.setError("Failed collect during installPackageLI", e);
16898            return;
16899        }
16900
16901        if (instantApp && pkg.mSigningDetails.signatureSchemeVersion
16902                < SignatureSchemeVersion.SIGNING_BLOCK_V2) {
16903            Slog.w(TAG, "Instant app package " + pkg.packageName
16904                    + " is not signed with at least APK Signature Scheme v2");
16905            res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16906                    "Instant app package must be signed with APK Signature Scheme v2 or greater");
16907            return;
16908        }
16909
16910        // Get rid of all references to package scan path via parser.
16911        pp = null;
16912        String oldCodePath = null;
16913        boolean systemApp = false;
16914        synchronized (mPackages) {
16915            // Check if installing already existing package
16916            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16917                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16918                if (pkg.mOriginalPackages != null
16919                        && pkg.mOriginalPackages.contains(oldName)
16920                        && mPackages.containsKey(oldName)) {
16921                    // This package is derived from an original package,
16922                    // and this device has been updating from that original
16923                    // name.  We must continue using the original name, so
16924                    // rename the new package here.
16925                    pkg.setPackageName(oldName);
16926                    pkgName = pkg.packageName;
16927                    replace = true;
16928                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16929                            + oldName + " pkgName=" + pkgName);
16930                } else if (mPackages.containsKey(pkgName)) {
16931                    // This package, under its official name, already exists
16932                    // on the device; we should replace it.
16933                    replace = true;
16934                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16935                }
16936
16937                // Child packages are installed through the parent package
16938                if (pkg.parentPackage != null) {
16939                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16940                            "Package " + pkg.packageName + " is child of package "
16941                                    + pkg.parentPackage.parentPackage + ". Child packages "
16942                                    + "can be updated only through the parent package.");
16943                    return;
16944                }
16945
16946                if (replace) {
16947                    // Prevent apps opting out from runtime permissions
16948                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16949                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16950                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16951                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16952                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16953                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16954                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16955                                        + " doesn't support runtime permissions but the old"
16956                                        + " target SDK " + oldTargetSdk + " does.");
16957                        return;
16958                    }
16959                    // Prevent persistent apps from being updated
16960                    if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) {
16961                        res.setError(PackageManager.INSTALL_FAILED_INVALID_APK,
16962                                "Package " + oldPackage.packageName + " is a persistent app. "
16963                                        + "Persistent apps are not updateable.");
16964                        return;
16965                    }
16966                    // Prevent apps from downgrading their targetSandbox.
16967                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
16968                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
16969                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
16970                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16971                                "Package " + pkg.packageName + " new target sandbox "
16972                                + newTargetSandbox + " is incompatible with the previous value of"
16973                                + oldTargetSandbox + ".");
16974                        return;
16975                    }
16976
16977                    // Prevent installing of child packages
16978                    if (oldPackage.parentPackage != null) {
16979                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16980                                "Package " + pkg.packageName + " is child of package "
16981                                        + oldPackage.parentPackage + ". Child packages "
16982                                        + "can be updated only through the parent package.");
16983                        return;
16984                    }
16985                }
16986            }
16987
16988            PackageSetting ps = mSettings.mPackages.get(pkgName);
16989            if (ps != null) {
16990                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16991
16992                // Static shared libs have same package with different versions where
16993                // we internally use a synthetic package name to allow multiple versions
16994                // of the same package, therefore we need to compare signatures against
16995                // the package setting for the latest library version.
16996                PackageSetting signatureCheckPs = ps;
16997                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16998                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16999                    if (libraryEntry != null) {
17000                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17001                    }
17002                }
17003
17004                // Quick sanity check that we're signed correctly if updating;
17005                // we'll check this again later when scanning, but we want to
17006                // bail early here before tripping over redefined permissions.
17007                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17008                if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
17009                    if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
17010                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17011                                + pkg.packageName + " upgrade keys do not match the "
17012                                + "previously installed version");
17013                        return;
17014                    }
17015                } else {
17016                    try {
17017                        final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
17018                        final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
17019                        // We don't care about disabledPkgSetting on install for now.
17020                        final boolean compatMatch = verifySignatures(
17021                                signatureCheckPs, null, pkg.mSigningDetails, compareCompat,
17022                                compareRecover);
17023                        // The new KeySets will be re-added later in the scanning process.
17024                        if (compatMatch) {
17025                            synchronized (mPackages) {
17026                                ksms.removeAppKeySetDataLPw(pkg.packageName);
17027                            }
17028                        }
17029                    } catch (PackageManagerException e) {
17030                        res.setError(e.error, e.getMessage());
17031                        return;
17032                    }
17033                }
17034
17035                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17036                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17037                    systemApp = (ps.pkg.applicationInfo.flags &
17038                            ApplicationInfo.FLAG_SYSTEM) != 0;
17039                }
17040                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17041            }
17042
17043            int N = pkg.permissions.size();
17044            for (int i = N-1; i >= 0; i--) {
17045                final PackageParser.Permission perm = pkg.permissions.get(i);
17046                final BasePermission bp =
17047                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
17048
17049                // Don't allow anyone but the system to define ephemeral permissions.
17050                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
17051                        && !systemApp) {
17052                    Slog.w(TAG, "Non-System package " + pkg.packageName
17053                            + " attempting to delcare ephemeral permission "
17054                            + perm.info.name + "; Removing ephemeral.");
17055                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
17056                }
17057
17058                // Check whether the newly-scanned package wants to define an already-defined perm
17059                if (bp != null) {
17060                    // If the defining package is signed with our cert, it's okay.  This
17061                    // also includes the "updating the same package" case, of course.
17062                    // "updating same package" could also involve key-rotation.
17063                    final boolean sigsOk;
17064                    final String sourcePackageName = bp.getSourcePackageName();
17065                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
17066                    final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17067                    if (sourcePackageName.equals(pkg.packageName)
17068                            && (ksms.shouldCheckUpgradeKeySetLocked(
17069                                    sourcePackageSetting, scanFlags))) {
17070                        sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg);
17071                    } else {
17072                        sigsOk = compareSignatures(
17073                                sourcePackageSetting.signatures.mSigningDetails.signatures,
17074                                pkg.mSigningDetails.signatures) == PackageManager.SIGNATURE_MATCH;
17075                    }
17076                    if (!sigsOk) {
17077                        // If the owning package is the system itself, we log but allow
17078                        // install to proceed; we fail the install on all other permission
17079                        // redefinitions.
17080                        if (!sourcePackageName.equals("android")) {
17081                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17082                                    + pkg.packageName + " attempting to redeclare permission "
17083                                    + perm.info.name + " already owned by " + sourcePackageName);
17084                            res.origPermission = perm.info.name;
17085                            res.origPackage = sourcePackageName;
17086                            return;
17087                        } else {
17088                            Slog.w(TAG, "Package " + pkg.packageName
17089                                    + " attempting to redeclare system permission "
17090                                    + perm.info.name + "; ignoring new declaration");
17091                            pkg.permissions.remove(i);
17092                        }
17093                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17094                        // Prevent apps to change protection level to dangerous from any other
17095                        // type as this would allow a privilege escalation where an app adds a
17096                        // normal/signature permission in other app's group and later redefines
17097                        // it as dangerous leading to the group auto-grant.
17098                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17099                                == PermissionInfo.PROTECTION_DANGEROUS) {
17100                            if (bp != null && !bp.isRuntime()) {
17101                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17102                                        + "non-runtime permission " + perm.info.name
17103                                        + " to runtime; keeping old protection level");
17104                                perm.info.protectionLevel = bp.getProtectionLevel();
17105                            }
17106                        }
17107                    }
17108                }
17109            }
17110        }
17111
17112        if (systemApp) {
17113            if (onExternal) {
17114                // Abort update; system app can't be replaced with app on sdcard
17115                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17116                        "Cannot install updates to system apps on sdcard");
17117                return;
17118            } else if (instantApp) {
17119                // Abort update; system app can't be replaced with an instant app
17120                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17121                        "Cannot update a system app with an instant app");
17122                return;
17123            }
17124        }
17125
17126        if (args.move != null) {
17127            // We did an in-place move, so dex is ready to roll
17128            scanFlags |= SCAN_NO_DEX;
17129            scanFlags |= SCAN_MOVE;
17130
17131            synchronized (mPackages) {
17132                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17133                if (ps == null) {
17134                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17135                            "Missing settings for moved package " + pkgName);
17136                }
17137
17138                // We moved the entire application as-is, so bring over the
17139                // previously derived ABI information.
17140                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17141                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17142            }
17143
17144        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17145            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17146            scanFlags |= SCAN_NO_DEX;
17147
17148            try {
17149                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17150                    args.abiOverride : pkg.cpuAbiOverride);
17151                final boolean extractNativeLibs = !pkg.isLibrary();
17152                derivePackageAbi(pkg, abiOverride, extractNativeLibs);
17153            } catch (PackageManagerException pme) {
17154                Slog.e(TAG, "Error deriving application ABI", pme);
17155                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17156                return;
17157            }
17158
17159            // Shared libraries for the package need to be updated.
17160            synchronized (mPackages) {
17161                try {
17162                    updateSharedLibrariesLPr(pkg, null);
17163                } catch (PackageManagerException e) {
17164                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17165                }
17166            }
17167        }
17168
17169        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17170            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17171            return;
17172        }
17173
17174        if (PackageManagerServiceUtils.isApkVerityEnabled()) {
17175            String apkPath = null;
17176            synchronized (mPackages) {
17177                // Note that if the attacker managed to skip verify setup, for example by tampering
17178                // with the package settings, upon reboot we will do full apk verification when
17179                // verity is not detected.
17180                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17181                if (ps != null && ps.isPrivileged()) {
17182                    apkPath = pkg.baseCodePath;
17183                }
17184            }
17185
17186            if (apkPath != null) {
17187                final VerityUtils.SetupResult result =
17188                        VerityUtils.generateApkVeritySetupData(apkPath);
17189                if (result.isOk()) {
17190                    if (Build.IS_DEBUGGABLE) Slog.i(TAG, "Enabling apk verity to " + apkPath);
17191                    FileDescriptor fd = result.getUnownedFileDescriptor();
17192                    try {
17193                        mInstaller.installApkVerity(apkPath, fd);
17194                    } catch (InstallerException e) {
17195                        res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17196                                "Failed to set up verity: " + e);
17197                        return;
17198                    } finally {
17199                        IoUtils.closeQuietly(fd);
17200                    }
17201                } else if (result.isFailed()) {
17202                    res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Failed to generate verity");
17203                    return;
17204                } else {
17205                    // Do nothing if verity is skipped. Will fall back to full apk verification on
17206                    // reboot.
17207                }
17208            }
17209        }
17210
17211        if (!instantApp) {
17212            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17213        } else {
17214            if (DEBUG_DOMAIN_VERIFICATION) {
17215                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
17216            }
17217        }
17218
17219        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17220                "installPackageLI")) {
17221            if (replace) {
17222                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17223                    // Static libs have a synthetic package name containing the version
17224                    // and cannot be updated as an update would get a new package name,
17225                    // unless this is the exact same version code which is useful for
17226                    // development.
17227                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17228                    if (existingPkg != null &&
17229                            existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) {
17230                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17231                                + "static-shared libs cannot be updated");
17232                        return;
17233                    }
17234                }
17235                replacePackageLIF(pkg, parseFlags, scanFlags, args.user,
17236                        installerPackageName, res, args.installReason);
17237            } else {
17238                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17239                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17240            }
17241        }
17242
17243        // Prepare the application profiles for the new code paths.
17244        // This needs to be done before invoking dexopt so that any install-time profile
17245        // can be used for optimizations.
17246        mArtManagerService.prepareAppProfiles(pkg, resolveUserIds(args.user.getIdentifier()));
17247
17248        // Check whether we need to dexopt the app.
17249        //
17250        // NOTE: it is IMPORTANT to call dexopt:
17251        //   - after doRename which will sync the package data from PackageParser.Package and its
17252        //     corresponding ApplicationInfo.
17253        //   - after installNewPackageLIF or replacePackageLIF which will update result with the
17254        //     uid of the application (pkg.applicationInfo.uid).
17255        //     This update happens in place!
17256        //
17257        // We only need to dexopt if the package meets ALL of the following conditions:
17258        //   1) it is not forward locked.
17259        //   2) it is not on on an external ASEC container.
17260        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
17261        //
17262        // Note that we do not dexopt instant apps by default. dexopt can take some time to
17263        // complete, so we skip this step during installation. Instead, we'll take extra time
17264        // the first time the instant app starts. It's preferred to do it this way to provide
17265        // continuous progress to the useur instead of mysteriously blocking somewhere in the
17266        // middle of running an instant app. The default behaviour can be overridden
17267        // via gservices.
17268        final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED)
17269                && !forwardLocked
17270                && !pkg.applicationInfo.isExternalAsec()
17271                && (!instantApp || Global.getInt(mContext.getContentResolver(),
17272                Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
17273
17274        if (performDexopt) {
17275            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17276            // Do not run PackageDexOptimizer through the local performDexOpt
17277            // method because `pkg` may not be in `mPackages` yet.
17278            //
17279            // Also, don't fail application installs if the dexopt step fails.
17280            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
17281                    REASON_INSTALL,
17282                    DexoptOptions.DEXOPT_BOOT_COMPLETE);
17283            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17284                    null /* instructionSets */,
17285                    getOrCreateCompilerPackageStats(pkg),
17286                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
17287                    dexoptOptions);
17288            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17289        }
17290
17291        // Notify BackgroundDexOptService that the package has been changed.
17292        // If this is an update of a package which used to fail to compile,
17293        // BackgroundDexOptService will remove it from its blacklist.
17294        // TODO: Layering violation
17295        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17296
17297        synchronized (mPackages) {
17298            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17299            if (ps != null) {
17300                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17301                ps.setUpdateAvailable(false /*updateAvailable*/);
17302            }
17303
17304            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17305            for (int i = 0; i < childCount; i++) {
17306                PackageParser.Package childPkg = pkg.childPackages.get(i);
17307                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17308                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17309                if (childPs != null) {
17310                    childRes.newUsers = childPs.queryInstalledUsers(
17311                            sUserManager.getUserIds(), true);
17312                }
17313            }
17314
17315            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17316                updateSequenceNumberLP(ps, res.newUsers);
17317                updateInstantAppInstallerLocked(pkgName);
17318            }
17319        }
17320    }
17321
17322    private void startIntentFilterVerifications(int userId, boolean replacing,
17323            PackageParser.Package pkg) {
17324        if (mIntentFilterVerifierComponent == null) {
17325            Slog.w(TAG, "No IntentFilter verification will not be done as "
17326                    + "there is no IntentFilterVerifier available!");
17327            return;
17328        }
17329
17330        final int verifierUid = getPackageUid(
17331                mIntentFilterVerifierComponent.getPackageName(),
17332                MATCH_DEBUG_TRIAGED_MISSING,
17333                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17334
17335        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17336        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17337        mHandler.sendMessage(msg);
17338
17339        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17340        for (int i = 0; i < childCount; i++) {
17341            PackageParser.Package childPkg = pkg.childPackages.get(i);
17342            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17343            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17344            mHandler.sendMessage(msg);
17345        }
17346    }
17347
17348    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17349            PackageParser.Package pkg) {
17350        int size = pkg.activities.size();
17351        if (size == 0) {
17352            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17353                    "No activity, so no need to verify any IntentFilter!");
17354            return;
17355        }
17356
17357        final boolean hasDomainURLs = hasDomainURLs(pkg);
17358        if (!hasDomainURLs) {
17359            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17360                    "No domain URLs, so no need to verify any IntentFilter!");
17361            return;
17362        }
17363
17364        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17365                + " if any IntentFilter from the " + size
17366                + " Activities needs verification ...");
17367
17368        int count = 0;
17369        final String packageName = pkg.packageName;
17370
17371        synchronized (mPackages) {
17372            // If this is a new install and we see that we've already run verification for this
17373            // package, we have nothing to do: it means the state was restored from backup.
17374            if (!replacing) {
17375                IntentFilterVerificationInfo ivi =
17376                        mSettings.getIntentFilterVerificationLPr(packageName);
17377                if (ivi != null) {
17378                    if (DEBUG_DOMAIN_VERIFICATION) {
17379                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17380                                + ivi.getStatusString());
17381                    }
17382                    return;
17383                }
17384            }
17385
17386            // If any filters need to be verified, then all need to be.
17387            boolean needToVerify = false;
17388            for (PackageParser.Activity a : pkg.activities) {
17389                for (ActivityIntentInfo filter : a.intents) {
17390                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17391                        if (DEBUG_DOMAIN_VERIFICATION) {
17392                            Slog.d(TAG,
17393                                    "Intent filter needs verification, so processing all filters");
17394                        }
17395                        needToVerify = true;
17396                        break;
17397                    }
17398                }
17399            }
17400
17401            if (needToVerify) {
17402                final int verificationId = mIntentFilterVerificationToken++;
17403                for (PackageParser.Activity a : pkg.activities) {
17404                    for (ActivityIntentInfo filter : a.intents) {
17405                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17406                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17407                                    "Verification needed for IntentFilter:" + filter.toString());
17408                            mIntentFilterVerifier.addOneIntentFilterVerification(
17409                                    verifierUid, userId, verificationId, filter, packageName);
17410                            count++;
17411                        }
17412                    }
17413                }
17414            }
17415        }
17416
17417        if (count > 0) {
17418            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17419                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17420                    +  " for userId:" + userId);
17421            mIntentFilterVerifier.startVerifications(userId);
17422        } else {
17423            if (DEBUG_DOMAIN_VERIFICATION) {
17424                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17425            }
17426        }
17427    }
17428
17429    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17430        final ComponentName cn  = filter.activity.getComponentName();
17431        final String packageName = cn.getPackageName();
17432
17433        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17434                packageName);
17435        if (ivi == null) {
17436            return true;
17437        }
17438        int status = ivi.getStatus();
17439        switch (status) {
17440            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17441            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17442                return true;
17443
17444            default:
17445                // Nothing to do
17446                return false;
17447        }
17448    }
17449
17450    private static boolean isMultiArch(ApplicationInfo info) {
17451        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17452    }
17453
17454    private static boolean isExternal(PackageParser.Package pkg) {
17455        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17456    }
17457
17458    private static boolean isExternal(PackageSetting ps) {
17459        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17460    }
17461
17462    private static boolean isSystemApp(PackageParser.Package pkg) {
17463        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17464    }
17465
17466    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17467        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17468    }
17469
17470    private static boolean isOemApp(PackageParser.Package pkg) {
17471        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17472    }
17473
17474    private static boolean isVendorApp(PackageParser.Package pkg) {
17475        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
17476    }
17477
17478    private static boolean isProductApp(PackageParser.Package pkg) {
17479        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
17480    }
17481
17482    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17483        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17484    }
17485
17486    private static boolean isSystemApp(PackageSetting ps) {
17487        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17488    }
17489
17490    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17491        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17492    }
17493
17494    private int packageFlagsToInstallFlags(PackageSetting ps) {
17495        int installFlags = 0;
17496        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17497            // This existing package was an external ASEC install when we have
17498            // the external flag without a UUID
17499            installFlags |= PackageManager.INSTALL_EXTERNAL;
17500        }
17501        if (ps.isForwardLocked()) {
17502            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17503        }
17504        return installFlags;
17505    }
17506
17507    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17508        if (isExternal(pkg)) {
17509            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17510                return mSettings.getExternalVersion();
17511            } else {
17512                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17513            }
17514        } else {
17515            return mSettings.getInternalVersion();
17516        }
17517    }
17518
17519    private void deleteTempPackageFiles() {
17520        final FilenameFilter filter = new FilenameFilter() {
17521            public boolean accept(File dir, String name) {
17522                return name.startsWith("vmdl") && name.endsWith(".tmp");
17523            }
17524        };
17525        for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) {
17526            file.delete();
17527        }
17528    }
17529
17530    @Override
17531    public void deletePackageAsUser(String packageName, int versionCode,
17532            IPackageDeleteObserver observer, int userId, int flags) {
17533        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17534                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17535    }
17536
17537    @Override
17538    public void deletePackageVersioned(VersionedPackage versionedPackage,
17539            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17540        final int callingUid = Binder.getCallingUid();
17541        mContext.enforceCallingOrSelfPermission(
17542                android.Manifest.permission.DELETE_PACKAGES, null);
17543        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
17544        Preconditions.checkNotNull(versionedPackage);
17545        Preconditions.checkNotNull(observer);
17546        Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(),
17547                PackageManager.VERSION_CODE_HIGHEST,
17548                Long.MAX_VALUE, "versionCode must be >= -1");
17549
17550        final String packageName = versionedPackage.getPackageName();
17551        final long versionCode = versionedPackage.getLongVersionCode();
17552        final String internalPackageName;
17553        synchronized (mPackages) {
17554            // Normalize package name to handle renamed packages and static libs
17555            internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode);
17556        }
17557
17558        final int uid = Binder.getCallingUid();
17559        if (!isOrphaned(internalPackageName)
17560                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17561            try {
17562                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17563                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17564                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17565                observer.onUserActionRequired(intent);
17566            } catch (RemoteException re) {
17567            }
17568            return;
17569        }
17570        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17571        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17572        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17573            mContext.enforceCallingOrSelfPermission(
17574                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17575                    "deletePackage for user " + userId);
17576        }
17577
17578        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17579            try {
17580                observer.onPackageDeleted(packageName,
17581                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17582            } catch (RemoteException re) {
17583            }
17584            return;
17585        }
17586
17587        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17588            try {
17589                observer.onPackageDeleted(packageName,
17590                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17591            } catch (RemoteException re) {
17592            }
17593            return;
17594        }
17595
17596        if (DEBUG_REMOVE) {
17597            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17598                    + " deleteAllUsers: " + deleteAllUsers + " version="
17599                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17600                    ? "VERSION_CODE_HIGHEST" : versionCode));
17601        }
17602        // Queue up an async operation since the package deletion may take a little while.
17603        mHandler.post(new Runnable() {
17604            public void run() {
17605                mHandler.removeCallbacks(this);
17606                int returnCode;
17607                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
17608                boolean doDeletePackage = true;
17609                if (ps != null) {
17610                    final boolean targetIsInstantApp =
17611                            ps.getInstantApp(UserHandle.getUserId(callingUid));
17612                    doDeletePackage = !targetIsInstantApp
17613                            || canViewInstantApps;
17614                }
17615                if (doDeletePackage) {
17616                    if (!deleteAllUsers) {
17617                        returnCode = deletePackageX(internalPackageName, versionCode,
17618                                userId, deleteFlags);
17619                    } else {
17620                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
17621                                internalPackageName, users);
17622                        // If nobody is blocking uninstall, proceed with delete for all users
17623                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17624                            returnCode = deletePackageX(internalPackageName, versionCode,
17625                                    userId, deleteFlags);
17626                        } else {
17627                            // Otherwise uninstall individually for users with blockUninstalls=false
17628                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17629                            for (int userId : users) {
17630                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17631                                    returnCode = deletePackageX(internalPackageName, versionCode,
17632                                            userId, userFlags);
17633                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17634                                        Slog.w(TAG, "Package delete failed for user " + userId
17635                                                + ", returnCode " + returnCode);
17636                                    }
17637                                }
17638                            }
17639                            // The app has only been marked uninstalled for certain users.
17640                            // We still need to report that delete was blocked
17641                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17642                        }
17643                    }
17644                } else {
17645                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17646                }
17647                try {
17648                    observer.onPackageDeleted(packageName, returnCode, null);
17649                } catch (RemoteException e) {
17650                    Log.i(TAG, "Observer no longer exists.");
17651                } //end catch
17652            } //end run
17653        });
17654    }
17655
17656    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17657        if (pkg.staticSharedLibName != null) {
17658            return pkg.manifestPackageName;
17659        }
17660        return pkg.packageName;
17661    }
17662
17663    private String resolveInternalPackageNameLPr(String packageName, long versionCode) {
17664        // Handle renamed packages
17665        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17666        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17667
17668        // Is this a static library?
17669        LongSparseArray<SharedLibraryEntry> versionedLib =
17670                mStaticLibsByDeclaringPackage.get(packageName);
17671        if (versionedLib == null || versionedLib.size() <= 0) {
17672            return packageName;
17673        }
17674
17675        // Figure out which lib versions the caller can see
17676        LongSparseLongArray versionsCallerCanSee = null;
17677        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17678        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17679                && callingAppId != Process.ROOT_UID) {
17680            versionsCallerCanSee = new LongSparseLongArray();
17681            String libName = versionedLib.valueAt(0).info.getName();
17682            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17683            if (uidPackages != null) {
17684                for (String uidPackage : uidPackages) {
17685                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17686                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17687                    if (libIdx >= 0) {
17688                        final long libVersion = ps.usesStaticLibrariesVersions[libIdx];
17689                        versionsCallerCanSee.append(libVersion, libVersion);
17690                    }
17691                }
17692            }
17693        }
17694
17695        // Caller can see nothing - done
17696        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17697            return packageName;
17698        }
17699
17700        // Find the version the caller can see and the app version code
17701        SharedLibraryEntry highestVersion = null;
17702        final int versionCount = versionedLib.size();
17703        for (int i = 0; i < versionCount; i++) {
17704            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17705            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17706                    libEntry.info.getLongVersion()) < 0) {
17707                continue;
17708            }
17709            final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode();
17710            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17711                if (libVersionCode == versionCode) {
17712                    return libEntry.apk;
17713                }
17714            } else if (highestVersion == null) {
17715                highestVersion = libEntry;
17716            } else if (libVersionCode  > highestVersion.info
17717                    .getDeclaringPackage().getLongVersionCode()) {
17718                highestVersion = libEntry;
17719            }
17720        }
17721
17722        if (highestVersion != null) {
17723            return highestVersion.apk;
17724        }
17725
17726        return packageName;
17727    }
17728
17729    boolean isCallerVerifier(int callingUid) {
17730        final int callingUserId = UserHandle.getUserId(callingUid);
17731        return mRequiredVerifierPackage != null &&
17732                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
17733    }
17734
17735    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17736        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17737              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17738            return true;
17739        }
17740        final int callingUserId = UserHandle.getUserId(callingUid);
17741        // If the caller installed the pkgName, then allow it to silently uninstall.
17742        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17743            return true;
17744        }
17745
17746        // Allow package verifier to silently uninstall.
17747        if (mRequiredVerifierPackage != null &&
17748                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17749            return true;
17750        }
17751
17752        // Allow package uninstaller to silently uninstall.
17753        if (mRequiredUninstallerPackage != null &&
17754                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17755            return true;
17756        }
17757
17758        // Allow storage manager to silently uninstall.
17759        if (mStorageManagerPackage != null &&
17760                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17761            return true;
17762        }
17763
17764        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
17765        // uninstall for device owner provisioning.
17766        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
17767                == PERMISSION_GRANTED) {
17768            return true;
17769        }
17770
17771        return false;
17772    }
17773
17774    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17775        int[] result = EMPTY_INT_ARRAY;
17776        for (int userId : userIds) {
17777            if (getBlockUninstallForUser(packageName, userId)) {
17778                result = ArrayUtils.appendInt(result, userId);
17779            }
17780        }
17781        return result;
17782    }
17783
17784    @Override
17785    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17786        final int callingUid = Binder.getCallingUid();
17787        if (getInstantAppPackageName(callingUid) != null
17788                && !isCallerSameApp(packageName, callingUid)) {
17789            return false;
17790        }
17791        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17792    }
17793
17794    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17795        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17796                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17797        try {
17798            if (dpm != null) {
17799                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17800                        /* callingUserOnly =*/ false);
17801                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17802                        : deviceOwnerComponentName.getPackageName();
17803                // Does the package contains the device owner?
17804                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17805                // this check is probably not needed, since DO should be registered as a device
17806                // admin on some user too. (Original bug for this: b/17657954)
17807                if (packageName.equals(deviceOwnerPackageName)) {
17808                    return true;
17809                }
17810                // Does it contain a device admin for any user?
17811                int[] users;
17812                if (userId == UserHandle.USER_ALL) {
17813                    users = sUserManager.getUserIds();
17814                } else {
17815                    users = new int[]{userId};
17816                }
17817                for (int i = 0; i < users.length; ++i) {
17818                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17819                        return true;
17820                    }
17821                }
17822            }
17823        } catch (RemoteException e) {
17824        }
17825        return false;
17826    }
17827
17828    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17829        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17830    }
17831
17832    /**
17833     *  This method is an internal method that could be get invoked either
17834     *  to delete an installed package or to clean up a failed installation.
17835     *  After deleting an installed package, a broadcast is sent to notify any
17836     *  listeners that the package has been removed. For cleaning up a failed
17837     *  installation, the broadcast is not necessary since the package's
17838     *  installation wouldn't have sent the initial broadcast either
17839     *  The key steps in deleting a package are
17840     *  deleting the package information in internal structures like mPackages,
17841     *  deleting the packages base directories through installd
17842     *  updating mSettings to reflect current status
17843     *  persisting settings for later use
17844     *  sending a broadcast if necessary
17845     */
17846    int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) {
17847        final PackageRemovedInfo info = new PackageRemovedInfo(this);
17848        final boolean res;
17849
17850        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17851                ? UserHandle.USER_ALL : userId;
17852
17853        if (isPackageDeviceAdmin(packageName, removeUser)) {
17854            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17855            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17856        }
17857
17858        PackageSetting uninstalledPs = null;
17859        PackageParser.Package pkg = null;
17860
17861        // for the uninstall-updates case and restricted profiles, remember the per-
17862        // user handle installed state
17863        int[] allUsers;
17864        synchronized (mPackages) {
17865            uninstalledPs = mSettings.mPackages.get(packageName);
17866            if (uninstalledPs == null) {
17867                Slog.w(TAG, "Not removing non-existent package " + packageName);
17868                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17869            }
17870
17871            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17872                    && uninstalledPs.versionCode != versionCode) {
17873                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17874                        + uninstalledPs.versionCode + " != " + versionCode);
17875                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17876            }
17877
17878            // Static shared libs can be declared by any package, so let us not
17879            // allow removing a package if it provides a lib others depend on.
17880            pkg = mPackages.get(packageName);
17881
17882            allUsers = sUserManager.getUserIds();
17883
17884            if (pkg != null && pkg.staticSharedLibName != null) {
17885                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17886                        pkg.staticSharedLibVersion);
17887                if (libEntry != null) {
17888                    for (int currUserId : allUsers) {
17889                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
17890                            continue;
17891                        }
17892                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17893                                libEntry.info, 0, currUserId);
17894                        if (!ArrayUtils.isEmpty(libClientPackages)) {
17895                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17896                                    + " hosting lib " + libEntry.info.getName() + " version "
17897                                    + libEntry.info.getLongVersion() + " used by " + libClientPackages
17898                                    + " for user " + currUserId);
17899                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17900                        }
17901                    }
17902                }
17903            }
17904
17905            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17906        }
17907
17908        final int freezeUser;
17909        if (isUpdatedSystemApp(uninstalledPs)
17910                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17911            // We're downgrading a system app, which will apply to all users, so
17912            // freeze them all during the downgrade
17913            freezeUser = UserHandle.USER_ALL;
17914        } else {
17915            freezeUser = removeUser;
17916        }
17917
17918        synchronized (mInstallLock) {
17919            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17920            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17921                    deleteFlags, "deletePackageX")) {
17922                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17923                        deleteFlags | PackageManager.DELETE_CHATTY, info, true, null);
17924            }
17925            synchronized (mPackages) {
17926                if (res) {
17927                    if (pkg != null) {
17928                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
17929                    }
17930                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
17931                    updateInstantAppInstallerLocked(packageName);
17932                }
17933            }
17934        }
17935
17936        if (res) {
17937            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17938            info.sendPackageRemovedBroadcasts(killApp);
17939            info.sendSystemPackageUpdatedBroadcasts();
17940            info.sendSystemPackageAppearedBroadcasts();
17941        }
17942        // Force a gc here.
17943        Runtime.getRuntime().gc();
17944        // Delete the resources here after sending the broadcast to let
17945        // other processes clean up before deleting resources.
17946        if (info.args != null) {
17947            synchronized (mInstallLock) {
17948                info.args.doPostDeleteLI(true);
17949            }
17950        }
17951
17952        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17953    }
17954
17955    static class PackageRemovedInfo {
17956        final PackageSender packageSender;
17957        String removedPackage;
17958        String installerPackageName;
17959        int uid = -1;
17960        int removedAppId = -1;
17961        int[] origUsers;
17962        int[] removedUsers = null;
17963        int[] broadcastUsers = null;
17964        int[] instantUserIds = null;
17965        SparseArray<Integer> installReasons;
17966        boolean isRemovedPackageSystemUpdate = false;
17967        boolean isUpdate;
17968        boolean dataRemoved;
17969        boolean removedForAllUsers;
17970        boolean isStaticSharedLib;
17971        // Clean up resources deleted packages.
17972        InstallArgs args = null;
17973        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17974        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17975
17976        PackageRemovedInfo(PackageSender packageSender) {
17977            this.packageSender = packageSender;
17978        }
17979
17980        void sendPackageRemovedBroadcasts(boolean killApp) {
17981            sendPackageRemovedBroadcastInternal(killApp);
17982            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17983            for (int i = 0; i < childCount; i++) {
17984                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17985                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17986            }
17987        }
17988
17989        void sendSystemPackageUpdatedBroadcasts() {
17990            if (isRemovedPackageSystemUpdate) {
17991                sendSystemPackageUpdatedBroadcastsInternal();
17992                final int childCount = (removedChildPackages != null)
17993                        ? removedChildPackages.size() : 0;
17994                for (int i = 0; i < childCount; i++) {
17995                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17996                    if (childInfo.isRemovedPackageSystemUpdate) {
17997                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17998                    }
17999                }
18000            }
18001        }
18002
18003        void sendSystemPackageAppearedBroadcasts() {
18004            final int packageCount = (appearedChildPackages != null)
18005                    ? appearedChildPackages.size() : 0;
18006            for (int i = 0; i < packageCount; i++) {
18007                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18008                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18009                    true /*sendBootCompleted*/, false /*startReceiver*/,
18010                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null);
18011            }
18012        }
18013
18014        private void sendSystemPackageUpdatedBroadcastsInternal() {
18015            Bundle extras = new Bundle(2);
18016            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18017            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18018            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18019                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18020            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18021                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18022            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18023                null, null, 0, removedPackage, null, null, null);
18024            if (installerPackageName != null) {
18025                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18026                        removedPackage, extras, 0 /*flags*/,
18027                        installerPackageName, null, null, null);
18028                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18029                        removedPackage, extras, 0 /*flags*/,
18030                        installerPackageName, null, null, null);
18031            }
18032        }
18033
18034        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18035            // Don't send static shared library removal broadcasts as these
18036            // libs are visible only the the apps that depend on them an one
18037            // cannot remove the library if it has a dependency.
18038            if (isStaticSharedLib) {
18039                return;
18040            }
18041            Bundle extras = new Bundle(2);
18042            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18043            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18044            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18045            if (isUpdate || isRemovedPackageSystemUpdate) {
18046                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18047            }
18048            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18049            if (removedPackage != null) {
18050                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18051                    removedPackage, extras, 0, null /*targetPackage*/, null,
18052                    broadcastUsers, instantUserIds);
18053                if (installerPackageName != null) {
18054                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18055                            removedPackage, extras, 0 /*flags*/,
18056                            installerPackageName, null, broadcastUsers, instantUserIds);
18057                }
18058                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18059                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18060                        removedPackage, extras,
18061                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18062                        null, null, broadcastUsers, instantUserIds);
18063                    packageSender.notifyPackageRemoved(removedPackage);
18064                }
18065            }
18066            if (removedAppId >= 0) {
18067                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
18068                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18069                    null, null, broadcastUsers, instantUserIds);
18070            }
18071        }
18072
18073        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18074            removedUsers = userIds;
18075            if (removedUsers == null) {
18076                broadcastUsers = null;
18077                return;
18078            }
18079
18080            broadcastUsers = EMPTY_INT_ARRAY;
18081            instantUserIds = EMPTY_INT_ARRAY;
18082            for (int i = userIds.length - 1; i >= 0; --i) {
18083                final int userId = userIds[i];
18084                if (deletedPackageSetting.getInstantApp(userId)) {
18085                    instantUserIds = ArrayUtils.appendInt(instantUserIds, userId);
18086                } else {
18087                    broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18088                }
18089            }
18090        }
18091    }
18092
18093    /*
18094     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18095     * flag is not set, the data directory is removed as well.
18096     * make sure this flag is set for partially installed apps. If not its meaningless to
18097     * delete a partially installed application.
18098     */
18099    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18100            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18101        String packageName = ps.name;
18102        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18103        // Retrieve object to delete permissions for shared user later on
18104        final PackageParser.Package deletedPkg;
18105        final PackageSetting deletedPs;
18106        // reader
18107        synchronized (mPackages) {
18108            deletedPkg = mPackages.get(packageName);
18109            deletedPs = mSettings.mPackages.get(packageName);
18110            if (outInfo != null) {
18111                outInfo.removedPackage = packageName;
18112                outInfo.installerPackageName = ps.installerPackageName;
18113                outInfo.isStaticSharedLib = deletedPkg != null
18114                        && deletedPkg.staticSharedLibName != null;
18115                outInfo.populateUsers(deletedPs == null ? null
18116                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18117            }
18118        }
18119
18120        removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0);
18121
18122        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18123            final PackageParser.Package resolvedPkg;
18124            if (deletedPkg != null) {
18125                resolvedPkg = deletedPkg;
18126            } else {
18127                // We don't have a parsed package when it lives on an ejected
18128                // adopted storage device, so fake something together
18129                resolvedPkg = new PackageParser.Package(ps.name);
18130                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18131            }
18132            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18133                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18134            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18135            if (outInfo != null) {
18136                outInfo.dataRemoved = true;
18137            }
18138            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18139        }
18140
18141        int removedAppId = -1;
18142
18143        // writer
18144        synchronized (mPackages) {
18145            boolean installedStateChanged = false;
18146            if (deletedPs != null) {
18147                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18148                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18149                    clearDefaultBrowserIfNeeded(packageName);
18150                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18151                    removedAppId = mSettings.removePackageLPw(packageName);
18152                    if (outInfo != null) {
18153                        outInfo.removedAppId = removedAppId;
18154                    }
18155                    mPermissionManager.updatePermissions(
18156                            deletedPs.name, null, false, mPackages.values(), mPermissionCallback);
18157                    if (deletedPs.sharedUser != null) {
18158                        // Remove permissions associated with package. Since runtime
18159                        // permissions are per user we have to kill the removed package
18160                        // or packages running under the shared user of the removed
18161                        // package if revoking the permissions requested only by the removed
18162                        // package is successful and this causes a change in gids.
18163                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18164                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18165                                    userId);
18166                            if (userIdToKill == UserHandle.USER_ALL
18167                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18168                                // If gids changed for this user, kill all affected packages.
18169                                mHandler.post(new Runnable() {
18170                                    @Override
18171                                    public void run() {
18172                                        // This has to happen with no lock held.
18173                                        killApplication(deletedPs.name, deletedPs.appId,
18174                                                KILL_APP_REASON_GIDS_CHANGED);
18175                                    }
18176                                });
18177                                break;
18178                            }
18179                        }
18180                    }
18181                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18182                }
18183                // make sure to preserve per-user disabled state if this removal was just
18184                // a downgrade of a system app to the factory package
18185                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18186                    if (DEBUG_REMOVE) {
18187                        Slog.d(TAG, "Propagating install state across downgrade");
18188                    }
18189                    for (int userId : allUserHandles) {
18190                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18191                        if (DEBUG_REMOVE) {
18192                            Slog.d(TAG, "    user " + userId + " => " + installed);
18193                        }
18194                        if (installed != ps.getInstalled(userId)) {
18195                            installedStateChanged = true;
18196                        }
18197                        ps.setInstalled(installed, userId);
18198                    }
18199                }
18200            }
18201            // can downgrade to reader
18202            if (writeSettings) {
18203                // Save settings now
18204                mSettings.writeLPr();
18205            }
18206            if (installedStateChanged) {
18207                mSettings.writeKernelMappingLPr(ps);
18208            }
18209        }
18210        if (removedAppId != -1) {
18211            // A user ID was deleted here. Go through all users and remove it
18212            // from KeyStore.
18213            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18214        }
18215    }
18216
18217    static boolean locationIsPrivileged(String path) {
18218        try {
18219            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
18220            final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
18221            final File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
18222            return path.startsWith(privilegedAppDir.getCanonicalPath())
18223                    || path.startsWith(privilegedVendorAppDir.getCanonicalPath())
18224                    || path.startsWith(privilegedProductAppDir.getCanonicalPath());
18225        } catch (IOException e) {
18226            Slog.e(TAG, "Unable to access code path " + path);
18227        }
18228        return false;
18229    }
18230
18231    static boolean locationIsOem(String path) {
18232        try {
18233            return path.startsWith(Environment.getOemDirectory().getCanonicalPath());
18234        } catch (IOException e) {
18235            Slog.e(TAG, "Unable to access code path " + path);
18236        }
18237        return false;
18238    }
18239
18240    static boolean locationIsVendor(String path) {
18241        try {
18242            return path.startsWith(Environment.getVendorDirectory().getCanonicalPath());
18243        } catch (IOException e) {
18244            Slog.e(TAG, "Unable to access code path " + path);
18245        }
18246        return false;
18247    }
18248
18249    static boolean locationIsProduct(String path) {
18250        try {
18251            return path.startsWith(Environment.getProductDirectory().getCanonicalPath());
18252        } catch (IOException e) {
18253            Slog.e(TAG, "Unable to access code path " + path);
18254        }
18255        return false;
18256    }
18257
18258    /*
18259     * Tries to delete system package.
18260     */
18261    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18262            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18263            boolean writeSettings) {
18264        if (deletedPs.parentPackageName != null) {
18265            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18266            return false;
18267        }
18268
18269        final boolean applyUserRestrictions
18270                = (allUserHandles != null) && (outInfo.origUsers != null);
18271        final PackageSetting disabledPs;
18272        // Confirm if the system package has been updated
18273        // An updated system app can be deleted. This will also have to restore
18274        // the system pkg from system partition
18275        // reader
18276        synchronized (mPackages) {
18277            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18278        }
18279
18280        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18281                + " disabledPs=" + disabledPs);
18282
18283        if (disabledPs == null) {
18284            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18285            return false;
18286        } else if (DEBUG_REMOVE) {
18287            Slog.d(TAG, "Deleting system pkg from data partition");
18288        }
18289
18290        if (DEBUG_REMOVE) {
18291            if (applyUserRestrictions) {
18292                Slog.d(TAG, "Remembering install states:");
18293                for (int userId : allUserHandles) {
18294                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18295                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18296                }
18297            }
18298        }
18299
18300        // Delete the updated package
18301        outInfo.isRemovedPackageSystemUpdate = true;
18302        if (outInfo.removedChildPackages != null) {
18303            final int childCount = (deletedPs.childPackageNames != null)
18304                    ? deletedPs.childPackageNames.size() : 0;
18305            for (int i = 0; i < childCount; i++) {
18306                String childPackageName = deletedPs.childPackageNames.get(i);
18307                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18308                        .contains(childPackageName)) {
18309                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18310                            childPackageName);
18311                    if (childInfo != null) {
18312                        childInfo.isRemovedPackageSystemUpdate = true;
18313                    }
18314                }
18315            }
18316        }
18317
18318        if (disabledPs.versionCode < deletedPs.versionCode) {
18319            // Delete data for downgrades
18320            flags &= ~PackageManager.DELETE_KEEP_DATA;
18321        } else {
18322            // Preserve data by setting flag
18323            flags |= PackageManager.DELETE_KEEP_DATA;
18324        }
18325
18326        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18327                outInfo, writeSettings, disabledPs.pkg);
18328        if (!ret) {
18329            return false;
18330        }
18331
18332        // writer
18333        synchronized (mPackages) {
18334            // NOTE: The system package always needs to be enabled; even if it's for
18335            // a compressed stub. If we don't, installing the system package fails
18336            // during scan [scanning checks the disabled packages]. We will reverse
18337            // this later, after we've "installed" the stub.
18338            // Reinstate the old system package
18339            enableSystemPackageLPw(disabledPs.pkg);
18340            // Remove any native libraries from the upgraded package.
18341            removeNativeBinariesLI(deletedPs);
18342        }
18343
18344        // Install the system package
18345        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18346        try {
18347            installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles,
18348                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
18349        } catch (PackageManagerException e) {
18350            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18351                    + e.getMessage());
18352            return false;
18353        } finally {
18354            if (disabledPs.pkg.isStub) {
18355                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
18356            }
18357        }
18358        return true;
18359    }
18360
18361    /**
18362     * Installs a package that's already on the system partition.
18363     */
18364    private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString,
18365            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
18366            @Nullable PermissionsState origPermissionState, boolean writeSettings)
18367                    throws PackageManagerException {
18368        @ParseFlags int parseFlags =
18369                mDefParseFlags
18370                | PackageParser.PARSE_MUST_BE_APK
18371                | PackageParser.PARSE_IS_SYSTEM_DIR;
18372        @ScanFlags int scanFlags = SCAN_AS_SYSTEM;
18373        if (isPrivileged || locationIsPrivileged(codePathString)) {
18374            scanFlags |= SCAN_AS_PRIVILEGED;
18375        }
18376        if (locationIsOem(codePathString)) {
18377            scanFlags |= SCAN_AS_OEM;
18378        }
18379        if (locationIsVendor(codePathString)) {
18380            scanFlags |= SCAN_AS_VENDOR;
18381        }
18382        if (locationIsProduct(codePathString)) {
18383            scanFlags |= SCAN_AS_PRODUCT;
18384        }
18385
18386        final File codePath = new File(codePathString);
18387        final PackageParser.Package pkg =
18388                scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null);
18389
18390        try {
18391            // update shared libraries for the newly re-installed system package
18392            updateSharedLibrariesLPr(pkg, null);
18393        } catch (PackageManagerException e) {
18394            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18395        }
18396
18397        prepareAppDataAfterInstallLIF(pkg);
18398
18399        // writer
18400        synchronized (mPackages) {
18401            PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
18402
18403            // Propagate the permissions state as we do not want to drop on the floor
18404            // runtime permissions. The update permissions method below will take
18405            // care of removing obsolete permissions and grant install permissions.
18406            if (origPermissionState != null) {
18407                ps.getPermissionsState().copyFrom(origPermissionState);
18408            }
18409            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
18410                    mPermissionCallback);
18411
18412            final boolean applyUserRestrictions
18413                    = (allUserHandles != null) && (origUserHandles != null);
18414            if (applyUserRestrictions) {
18415                boolean installedStateChanged = false;
18416                if (DEBUG_REMOVE) {
18417                    Slog.d(TAG, "Propagating install state across reinstall");
18418                }
18419                for (int userId : allUserHandles) {
18420                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
18421                    if (DEBUG_REMOVE) {
18422                        Slog.d(TAG, "    user " + userId + " => " + installed);
18423                    }
18424                    if (installed != ps.getInstalled(userId)) {
18425                        installedStateChanged = true;
18426                    }
18427                    ps.setInstalled(installed, userId);
18428
18429                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18430                }
18431                // Regardless of writeSettings we need to ensure that this restriction
18432                // state propagation is persisted
18433                mSettings.writeAllUsersPackageRestrictionsLPr();
18434                if (installedStateChanged) {
18435                    mSettings.writeKernelMappingLPr(ps);
18436                }
18437            }
18438            // can downgrade to reader here
18439            if (writeSettings) {
18440                mSettings.writeLPr();
18441            }
18442        }
18443        return pkg;
18444    }
18445
18446    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18447            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18448            PackageRemovedInfo outInfo, boolean writeSettings,
18449            PackageParser.Package replacingPackage) {
18450        synchronized (mPackages) {
18451            if (outInfo != null) {
18452                outInfo.uid = ps.appId;
18453            }
18454
18455            if (outInfo != null && outInfo.removedChildPackages != null) {
18456                final int childCount = (ps.childPackageNames != null)
18457                        ? ps.childPackageNames.size() : 0;
18458                for (int i = 0; i < childCount; i++) {
18459                    String childPackageName = ps.childPackageNames.get(i);
18460                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18461                    if (childPs == null) {
18462                        return false;
18463                    }
18464                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18465                            childPackageName);
18466                    if (childInfo != null) {
18467                        childInfo.uid = childPs.appId;
18468                    }
18469                }
18470            }
18471        }
18472
18473        // Delete package data from internal structures and also remove data if flag is set
18474        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18475
18476        // Delete the child packages data
18477        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18478        for (int i = 0; i < childCount; i++) {
18479            PackageSetting childPs;
18480            synchronized (mPackages) {
18481                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18482            }
18483            if (childPs != null) {
18484                PackageRemovedInfo childOutInfo = (outInfo != null
18485                        && outInfo.removedChildPackages != null)
18486                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18487                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18488                        && (replacingPackage != null
18489                        && !replacingPackage.hasChildPackage(childPs.name))
18490                        ? flags & ~DELETE_KEEP_DATA : flags;
18491                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18492                        deleteFlags, writeSettings);
18493            }
18494        }
18495
18496        // Delete application code and resources only for parent packages
18497        if (ps.parentPackageName == null) {
18498            if (deleteCodeAndResources && (outInfo != null)) {
18499                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18500                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18501                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18502            }
18503        }
18504
18505        return true;
18506    }
18507
18508    @Override
18509    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18510            int userId) {
18511        mContext.enforceCallingOrSelfPermission(
18512                android.Manifest.permission.DELETE_PACKAGES, null);
18513        synchronized (mPackages) {
18514            // Cannot block uninstall of static shared libs as they are
18515            // considered a part of the using app (emulating static linking).
18516            // Also static libs are installed always on internal storage.
18517            PackageParser.Package pkg = mPackages.get(packageName);
18518            if (pkg != null && pkg.staticSharedLibName != null) {
18519                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18520                        + " providing static shared library: " + pkg.staticSharedLibName);
18521                return false;
18522            }
18523            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18524            mSettings.writePackageRestrictionsLPr(userId);
18525        }
18526        return true;
18527    }
18528
18529    @Override
18530    public boolean getBlockUninstallForUser(String packageName, int userId) {
18531        synchronized (mPackages) {
18532            final PackageSetting ps = mSettings.mPackages.get(packageName);
18533            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
18534                return false;
18535            }
18536            return mSettings.getBlockUninstallLPr(userId, packageName);
18537        }
18538    }
18539
18540    @Override
18541    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18542        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
18543        synchronized (mPackages) {
18544            PackageSetting ps = mSettings.mPackages.get(packageName);
18545            if (ps == null) {
18546                Log.w(TAG, "Package doesn't exist: " + packageName);
18547                return false;
18548            }
18549            if (systemUserApp) {
18550                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18551            } else {
18552                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18553            }
18554            mSettings.writeLPr();
18555        }
18556        return true;
18557    }
18558
18559    /*
18560     * This method handles package deletion in general
18561     */
18562    private boolean deletePackageLIF(String packageName, UserHandle user,
18563            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18564            PackageRemovedInfo outInfo, boolean writeSettings,
18565            PackageParser.Package replacingPackage) {
18566        if (packageName == null) {
18567            Slog.w(TAG, "Attempt to delete null packageName.");
18568            return false;
18569        }
18570
18571        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18572
18573        PackageSetting ps;
18574        synchronized (mPackages) {
18575            ps = mSettings.mPackages.get(packageName);
18576            if (ps == null) {
18577                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18578                return false;
18579            }
18580
18581            if (ps.parentPackageName != null && (!isSystemApp(ps)
18582                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18583                if (DEBUG_REMOVE) {
18584                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18585                            + ((user == null) ? UserHandle.USER_ALL : user));
18586                }
18587                final int removedUserId = (user != null) ? user.getIdentifier()
18588                        : UserHandle.USER_ALL;
18589                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18590                    return false;
18591                }
18592                markPackageUninstalledForUserLPw(ps, user);
18593                scheduleWritePackageRestrictionsLocked(user);
18594                return true;
18595            }
18596        }
18597
18598        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18599                && user.getIdentifier() != UserHandle.USER_ALL)) {
18600            // The caller is asking that the package only be deleted for a single
18601            // user.  To do this, we just mark its uninstalled state and delete
18602            // its data. If this is a system app, we only allow this to happen if
18603            // they have set the special DELETE_SYSTEM_APP which requests different
18604            // semantics than normal for uninstalling system apps.
18605            markPackageUninstalledForUserLPw(ps, user);
18606
18607            if (!isSystemApp(ps)) {
18608                // Do not uninstall the APK if an app should be cached
18609                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18610                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18611                    // Other user still have this package installed, so all
18612                    // we need to do is clear this user's data and save that
18613                    // it is uninstalled.
18614                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18615                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18616                        return false;
18617                    }
18618                    scheduleWritePackageRestrictionsLocked(user);
18619                    return true;
18620                } else {
18621                    // We need to set it back to 'installed' so the uninstall
18622                    // broadcasts will be sent correctly.
18623                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18624                    ps.setInstalled(true, user.getIdentifier());
18625                    mSettings.writeKernelMappingLPr(ps);
18626                }
18627            } else {
18628                // This is a system app, so we assume that the
18629                // other users still have this package installed, so all
18630                // we need to do is clear this user's data and save that
18631                // it is uninstalled.
18632                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18633                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18634                    return false;
18635                }
18636                scheduleWritePackageRestrictionsLocked(user);
18637                return true;
18638            }
18639        }
18640
18641        // If we are deleting a composite package for all users, keep track
18642        // of result for each child.
18643        if (ps.childPackageNames != null && outInfo != null) {
18644            synchronized (mPackages) {
18645                final int childCount = ps.childPackageNames.size();
18646                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18647                for (int i = 0; i < childCount; i++) {
18648                    String childPackageName = ps.childPackageNames.get(i);
18649                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18650                    childInfo.removedPackage = childPackageName;
18651                    childInfo.installerPackageName = ps.installerPackageName;
18652                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18653                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18654                    if (childPs != null) {
18655                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18656                    }
18657                }
18658            }
18659        }
18660
18661        boolean ret = false;
18662        if (isSystemApp(ps)) {
18663            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18664            // When an updated system application is deleted we delete the existing resources
18665            // as well and fall back to existing code in system partition
18666            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18667        } else {
18668            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18669            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18670                    outInfo, writeSettings, replacingPackage);
18671        }
18672
18673        // Take a note whether we deleted the package for all users
18674        if (outInfo != null) {
18675            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18676            if (outInfo.removedChildPackages != null) {
18677                synchronized (mPackages) {
18678                    final int childCount = outInfo.removedChildPackages.size();
18679                    for (int i = 0; i < childCount; i++) {
18680                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18681                        if (childInfo != null) {
18682                            childInfo.removedForAllUsers = mPackages.get(
18683                                    childInfo.removedPackage) == null;
18684                        }
18685                    }
18686                }
18687            }
18688            // If we uninstalled an update to a system app there may be some
18689            // child packages that appeared as they are declared in the system
18690            // app but were not declared in the update.
18691            if (isSystemApp(ps)) {
18692                synchronized (mPackages) {
18693                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18694                    final int childCount = (updatedPs.childPackageNames != null)
18695                            ? updatedPs.childPackageNames.size() : 0;
18696                    for (int i = 0; i < childCount; i++) {
18697                        String childPackageName = updatedPs.childPackageNames.get(i);
18698                        if (outInfo.removedChildPackages == null
18699                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18700                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18701                            if (childPs == null) {
18702                                continue;
18703                            }
18704                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18705                            installRes.name = childPackageName;
18706                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18707                            installRes.pkg = mPackages.get(childPackageName);
18708                            installRes.uid = childPs.pkg.applicationInfo.uid;
18709                            if (outInfo.appearedChildPackages == null) {
18710                                outInfo.appearedChildPackages = new ArrayMap<>();
18711                            }
18712                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18713                        }
18714                    }
18715                }
18716            }
18717        }
18718
18719        return ret;
18720    }
18721
18722    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18723        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18724                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18725        for (int nextUserId : userIds) {
18726            if (DEBUG_REMOVE) {
18727                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18728            }
18729            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18730                    false /*installed*/,
18731                    true /*stopped*/,
18732                    true /*notLaunched*/,
18733                    false /*hidden*/,
18734                    false /*suspended*/,
18735                    false /*instantApp*/,
18736                    false /*virtualPreload*/,
18737                    null /*lastDisableAppCaller*/,
18738                    null /*enabledComponents*/,
18739                    null /*disabledComponents*/,
18740                    ps.readUserState(nextUserId).domainVerificationStatus,
18741                    0, PackageManager.INSTALL_REASON_UNKNOWN,
18742                    null /*harmfulAppWarning*/);
18743        }
18744        mSettings.writeKernelMappingLPr(ps);
18745    }
18746
18747    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18748            PackageRemovedInfo outInfo) {
18749        final PackageParser.Package pkg;
18750        synchronized (mPackages) {
18751            pkg = mPackages.get(ps.name);
18752        }
18753
18754        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18755                : new int[] {userId};
18756        for (int nextUserId : userIds) {
18757            if (DEBUG_REMOVE) {
18758                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18759                        + nextUserId);
18760            }
18761
18762            destroyAppDataLIF(pkg, userId,
18763                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18764            destroyAppProfilesLIF(pkg, userId);
18765            clearDefaultBrowserIfNeededForUser(ps.name, userId);
18766            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18767            schedulePackageCleaning(ps.name, nextUserId, false);
18768            synchronized (mPackages) {
18769                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18770                    scheduleWritePackageRestrictionsLocked(nextUserId);
18771                }
18772                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18773            }
18774        }
18775
18776        if (outInfo != null) {
18777            outInfo.removedPackage = ps.name;
18778            outInfo.installerPackageName = ps.installerPackageName;
18779            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18780            outInfo.removedAppId = ps.appId;
18781            outInfo.removedUsers = userIds;
18782            outInfo.broadcastUsers = userIds;
18783        }
18784
18785        return true;
18786    }
18787
18788    private final class ClearStorageConnection implements ServiceConnection {
18789        IMediaContainerService mContainerService;
18790
18791        @Override
18792        public void onServiceConnected(ComponentName name, IBinder service) {
18793            synchronized (this) {
18794                mContainerService = IMediaContainerService.Stub
18795                        .asInterface(Binder.allowBlocking(service));
18796                notifyAll();
18797            }
18798        }
18799
18800        @Override
18801        public void onServiceDisconnected(ComponentName name) {
18802        }
18803    }
18804
18805    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18806        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18807
18808        final boolean mounted;
18809        if (Environment.isExternalStorageEmulated()) {
18810            mounted = true;
18811        } else {
18812            final String status = Environment.getExternalStorageState();
18813
18814            mounted = status.equals(Environment.MEDIA_MOUNTED)
18815                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18816        }
18817
18818        if (!mounted) {
18819            return;
18820        }
18821
18822        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18823        int[] users;
18824        if (userId == UserHandle.USER_ALL) {
18825            users = sUserManager.getUserIds();
18826        } else {
18827            users = new int[] { userId };
18828        }
18829        final ClearStorageConnection conn = new ClearStorageConnection();
18830        if (mContext.bindServiceAsUser(
18831                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18832            try {
18833                for (int curUser : users) {
18834                    long timeout = SystemClock.uptimeMillis() + 5000;
18835                    synchronized (conn) {
18836                        long now;
18837                        while (conn.mContainerService == null &&
18838                                (now = SystemClock.uptimeMillis()) < timeout) {
18839                            try {
18840                                conn.wait(timeout - now);
18841                            } catch (InterruptedException e) {
18842                            }
18843                        }
18844                    }
18845                    if (conn.mContainerService == null) {
18846                        return;
18847                    }
18848
18849                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18850                    clearDirectory(conn.mContainerService,
18851                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18852                    if (allData) {
18853                        clearDirectory(conn.mContainerService,
18854                                userEnv.buildExternalStorageAppDataDirs(packageName));
18855                        clearDirectory(conn.mContainerService,
18856                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18857                    }
18858                }
18859            } finally {
18860                mContext.unbindService(conn);
18861            }
18862        }
18863    }
18864
18865    @Override
18866    public void clearApplicationProfileData(String packageName) {
18867        enforceSystemOrRoot("Only the system can clear all profile data");
18868
18869        final PackageParser.Package pkg;
18870        synchronized (mPackages) {
18871            pkg = mPackages.get(packageName);
18872        }
18873
18874        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18875            synchronized (mInstallLock) {
18876                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18877            }
18878        }
18879    }
18880
18881    @Override
18882    public void clearApplicationUserData(final String packageName,
18883            final IPackageDataObserver observer, final int userId) {
18884        mContext.enforceCallingOrSelfPermission(
18885                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18886
18887        final int callingUid = Binder.getCallingUid();
18888        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18889                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18890
18891        final PackageSetting ps = mSettings.getPackageLPr(packageName);
18892        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
18893        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18894            throw new SecurityException("Cannot clear data for a protected package: "
18895                    + packageName);
18896        }
18897        // Queue up an async operation since the package deletion may take a little while.
18898        mHandler.post(new Runnable() {
18899            public void run() {
18900                mHandler.removeCallbacks(this);
18901                final boolean succeeded;
18902                if (!filterApp) {
18903                    try (PackageFreezer freezer = freezePackage(packageName,
18904                            "clearApplicationUserData")) {
18905                        synchronized (mInstallLock) {
18906                            succeeded = clearApplicationUserDataLIF(packageName, userId);
18907                        }
18908                        clearExternalStorageDataSync(packageName, userId, true);
18909                        synchronized (mPackages) {
18910                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18911                                    packageName, userId);
18912                        }
18913                    }
18914                    if (succeeded) {
18915                        // invoke DeviceStorageMonitor's update method to clear any notifications
18916                        DeviceStorageMonitorInternal dsm = LocalServices
18917                                .getService(DeviceStorageMonitorInternal.class);
18918                        if (dsm != null) {
18919                            dsm.checkMemory();
18920                        }
18921                    }
18922                } else {
18923                    succeeded = false;
18924                }
18925                if (observer != null) {
18926                    try {
18927                        observer.onRemoveCompleted(packageName, succeeded);
18928                    } catch (RemoteException e) {
18929                        Log.i(TAG, "Observer no longer exists.");
18930                    }
18931                } //end if observer
18932            } //end run
18933        });
18934    }
18935
18936    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18937        if (packageName == null) {
18938            Slog.w(TAG, "Attempt to delete null packageName.");
18939            return false;
18940        }
18941
18942        // Try finding details about the requested package
18943        PackageParser.Package pkg;
18944        synchronized (mPackages) {
18945            pkg = mPackages.get(packageName);
18946            if (pkg == null) {
18947                final PackageSetting ps = mSettings.mPackages.get(packageName);
18948                if (ps != null) {
18949                    pkg = ps.pkg;
18950                }
18951            }
18952
18953            if (pkg == null) {
18954                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18955                return false;
18956            }
18957
18958            PackageSetting ps = (PackageSetting) pkg.mExtras;
18959            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18960        }
18961
18962        clearAppDataLIF(pkg, userId,
18963                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18964
18965        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18966        removeKeystoreDataIfNeeded(userId, appId);
18967
18968        UserManagerInternal umInternal = getUserManagerInternal();
18969        final int flags;
18970        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18971            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18972        } else if (umInternal.isUserRunning(userId)) {
18973            flags = StorageManager.FLAG_STORAGE_DE;
18974        } else {
18975            flags = 0;
18976        }
18977        prepareAppDataContentsLIF(pkg, userId, flags);
18978
18979        return true;
18980    }
18981
18982    /**
18983     * Reverts user permission state changes (permissions and flags) in
18984     * all packages for a given user.
18985     *
18986     * @param userId The device user for which to do a reset.
18987     */
18988    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18989        final int packageCount = mPackages.size();
18990        for (int i = 0; i < packageCount; i++) {
18991            PackageParser.Package pkg = mPackages.valueAt(i);
18992            PackageSetting ps = (PackageSetting) pkg.mExtras;
18993            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18994        }
18995    }
18996
18997    private void resetNetworkPolicies(int userId) {
18998        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18999    }
19000
19001    /**
19002     * Reverts user permission state changes (permissions and flags).
19003     *
19004     * @param ps The package for which to reset.
19005     * @param userId The device user for which to do a reset.
19006     */
19007    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19008            final PackageSetting ps, final int userId) {
19009        if (ps.pkg == null) {
19010            return;
19011        }
19012
19013        // These are flags that can change base on user actions.
19014        final int userSettableMask = FLAG_PERMISSION_USER_SET
19015                | FLAG_PERMISSION_USER_FIXED
19016                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19017                | FLAG_PERMISSION_REVIEW_REQUIRED;
19018
19019        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19020                | FLAG_PERMISSION_POLICY_FIXED;
19021
19022        boolean writeInstallPermissions = false;
19023        boolean writeRuntimePermissions = false;
19024
19025        final int permissionCount = ps.pkg.requestedPermissions.size();
19026        for (int i = 0; i < permissionCount; i++) {
19027            final String permName = ps.pkg.requestedPermissions.get(i);
19028            final BasePermission bp =
19029                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
19030            if (bp == null) {
19031                continue;
19032            }
19033
19034            // If shared user we just reset the state to which only this app contributed.
19035            if (ps.sharedUser != null) {
19036                boolean used = false;
19037                final int packageCount = ps.sharedUser.packages.size();
19038                for (int j = 0; j < packageCount; j++) {
19039                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19040                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19041                            && pkg.pkg.requestedPermissions.contains(permName)) {
19042                        used = true;
19043                        break;
19044                    }
19045                }
19046                if (used) {
19047                    continue;
19048                }
19049            }
19050
19051            final PermissionsState permissionsState = ps.getPermissionsState();
19052
19053            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
19054
19055            // Always clear the user settable flags.
19056            final boolean hasInstallState =
19057                    permissionsState.getInstallPermissionState(permName) != null;
19058            // If permission review is enabled and this is a legacy app, mark the
19059            // permission as requiring a review as this is the initial state.
19060            int flags = 0;
19061            if (mSettings.mPermissions.mPermissionReviewRequired
19062                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19063                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19064            }
19065            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19066                if (hasInstallState) {
19067                    writeInstallPermissions = true;
19068                } else {
19069                    writeRuntimePermissions = true;
19070                }
19071            }
19072
19073            // Below is only runtime permission handling.
19074            if (!bp.isRuntime()) {
19075                continue;
19076            }
19077
19078            // Never clobber system or policy.
19079            if ((oldFlags & policyOrSystemFlags) != 0) {
19080                continue;
19081            }
19082
19083            // If this permission was granted by default, make sure it is.
19084            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19085                if (permissionsState.grantRuntimePermission(bp, userId)
19086                        != PERMISSION_OPERATION_FAILURE) {
19087                    writeRuntimePermissions = true;
19088                }
19089            // If permission review is enabled the permissions for a legacy apps
19090            // are represented as constantly granted runtime ones, so don't revoke.
19091            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19092                // Otherwise, reset the permission.
19093                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19094                switch (revokeResult) {
19095                    case PERMISSION_OPERATION_SUCCESS:
19096                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19097                        writeRuntimePermissions = true;
19098                        final int appId = ps.appId;
19099                        mHandler.post(new Runnable() {
19100                            @Override
19101                            public void run() {
19102                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19103                            }
19104                        });
19105                    } break;
19106                }
19107            }
19108        }
19109
19110        // Synchronously write as we are taking permissions away.
19111        if (writeRuntimePermissions) {
19112            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19113        }
19114
19115        // Synchronously write as we are taking permissions away.
19116        if (writeInstallPermissions) {
19117            mSettings.writeLPr();
19118        }
19119    }
19120
19121    /**
19122     * Remove entries from the keystore daemon. Will only remove it if the
19123     * {@code appId} is valid.
19124     */
19125    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19126        if (appId < 0) {
19127            return;
19128        }
19129
19130        final KeyStore keyStore = KeyStore.getInstance();
19131        if (keyStore != null) {
19132            if (userId == UserHandle.USER_ALL) {
19133                for (final int individual : sUserManager.getUserIds()) {
19134                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19135                }
19136            } else {
19137                keyStore.clearUid(UserHandle.getUid(userId, appId));
19138            }
19139        } else {
19140            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19141        }
19142    }
19143
19144    @Override
19145    public void deleteApplicationCacheFiles(final String packageName,
19146            final IPackageDataObserver observer) {
19147        final int userId = UserHandle.getCallingUserId();
19148        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19149    }
19150
19151    @Override
19152    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19153            final IPackageDataObserver observer) {
19154        final int callingUid = Binder.getCallingUid();
19155        mContext.enforceCallingOrSelfPermission(
19156                android.Manifest.permission.DELETE_CACHE_FILES, null);
19157        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19158                /* requireFullPermission= */ true, /* checkShell= */ false,
19159                "delete application cache files");
19160        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
19161                android.Manifest.permission.ACCESS_INSTANT_APPS);
19162
19163        final PackageParser.Package pkg;
19164        synchronized (mPackages) {
19165            pkg = mPackages.get(packageName);
19166        }
19167
19168        // Queue up an async operation since the package deletion may take a little while.
19169        mHandler.post(new Runnable() {
19170            public void run() {
19171                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
19172                boolean doClearData = true;
19173                if (ps != null) {
19174                    final boolean targetIsInstantApp =
19175                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19176                    doClearData = !targetIsInstantApp
19177                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
19178                }
19179                if (doClearData) {
19180                    synchronized (mInstallLock) {
19181                        final int flags = StorageManager.FLAG_STORAGE_DE
19182                                | StorageManager.FLAG_STORAGE_CE;
19183                        // We're only clearing cache files, so we don't care if the
19184                        // app is unfrozen and still able to run
19185                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19186                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19187                    }
19188                    clearExternalStorageDataSync(packageName, userId, false);
19189                }
19190                if (observer != null) {
19191                    try {
19192                        observer.onRemoveCompleted(packageName, true);
19193                    } catch (RemoteException e) {
19194                        Log.i(TAG, "Observer no longer exists.");
19195                    }
19196                }
19197            }
19198        });
19199    }
19200
19201    @Override
19202    public void getPackageSizeInfo(final String packageName, int userHandle,
19203            final IPackageStatsObserver observer) {
19204        throw new UnsupportedOperationException(
19205                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19206    }
19207
19208    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19209        final PackageSetting ps;
19210        synchronized (mPackages) {
19211            ps = mSettings.mPackages.get(packageName);
19212            if (ps == null) {
19213                Slog.w(TAG, "Failed to find settings for " + packageName);
19214                return false;
19215            }
19216        }
19217
19218        final String[] packageNames = { packageName };
19219        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19220        final String[] codePaths = { ps.codePathString };
19221
19222        try {
19223            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19224                    ps.appId, ceDataInodes, codePaths, stats);
19225
19226            // For now, ignore code size of packages on system partition
19227            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19228                stats.codeSize = 0;
19229            }
19230
19231            // External clients expect these to be tracked separately
19232            stats.dataSize -= stats.cacheSize;
19233
19234        } catch (InstallerException e) {
19235            Slog.w(TAG, String.valueOf(e));
19236            return false;
19237        }
19238
19239        return true;
19240    }
19241
19242    private int getUidTargetSdkVersionLockedLPr(int uid) {
19243        Object obj = mSettings.getUserIdLPr(uid);
19244        if (obj instanceof SharedUserSetting) {
19245            final SharedUserSetting sus = (SharedUserSetting) obj;
19246            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19247            final Iterator<PackageSetting> it = sus.packages.iterator();
19248            while (it.hasNext()) {
19249                final PackageSetting ps = it.next();
19250                if (ps.pkg != null) {
19251                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19252                    if (v < vers) vers = v;
19253                }
19254            }
19255            return vers;
19256        } else if (obj instanceof PackageSetting) {
19257            final PackageSetting ps = (PackageSetting) obj;
19258            if (ps.pkg != null) {
19259                return ps.pkg.applicationInfo.targetSdkVersion;
19260            }
19261        }
19262        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19263    }
19264
19265    private int getPackageTargetSdkVersionLockedLPr(String packageName) {
19266        final PackageParser.Package p = mPackages.get(packageName);
19267        if (p != null) {
19268            return p.applicationInfo.targetSdkVersion;
19269        }
19270        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19271    }
19272
19273    @Override
19274    public void addPreferredActivity(IntentFilter filter, int match,
19275            ComponentName[] set, ComponentName activity, int userId) {
19276        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19277                "Adding preferred");
19278    }
19279
19280    private void addPreferredActivityInternal(IntentFilter filter, int match,
19281            ComponentName[] set, ComponentName activity, boolean always, int userId,
19282            String opname) {
19283        // writer
19284        int callingUid = Binder.getCallingUid();
19285        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19286                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19287        if (filter.countActions() == 0) {
19288            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19289            return;
19290        }
19291        synchronized (mPackages) {
19292            if (mContext.checkCallingOrSelfPermission(
19293                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19294                    != PackageManager.PERMISSION_GRANTED) {
19295                if (getUidTargetSdkVersionLockedLPr(callingUid)
19296                        < Build.VERSION_CODES.FROYO) {
19297                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19298                            + callingUid);
19299                    return;
19300                }
19301                mContext.enforceCallingOrSelfPermission(
19302                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19303            }
19304
19305            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19306            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19307                    + userId + ":");
19308            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19309            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19310            scheduleWritePackageRestrictionsLocked(userId);
19311            postPreferredActivityChangedBroadcast(userId);
19312        }
19313    }
19314
19315    private void postPreferredActivityChangedBroadcast(int userId) {
19316        mHandler.post(() -> {
19317            final IActivityManager am = ActivityManager.getService();
19318            if (am == null) {
19319                return;
19320            }
19321
19322            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19323            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19324            try {
19325                am.broadcastIntent(null, intent, null, null,
19326                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19327                        null, false, false, userId);
19328            } catch (RemoteException e) {
19329            }
19330        });
19331    }
19332
19333    @Override
19334    public void replacePreferredActivity(IntentFilter filter, int match,
19335            ComponentName[] set, ComponentName activity, int userId) {
19336        if (filter.countActions() != 1) {
19337            throw new IllegalArgumentException(
19338                    "replacePreferredActivity expects filter to have only 1 action.");
19339        }
19340        if (filter.countDataAuthorities() != 0
19341                || filter.countDataPaths() != 0
19342                || filter.countDataSchemes() > 1
19343                || filter.countDataTypes() != 0) {
19344            throw new IllegalArgumentException(
19345                    "replacePreferredActivity expects filter to have no data authorities, " +
19346                    "paths, or types; and at most one scheme.");
19347        }
19348
19349        final int callingUid = Binder.getCallingUid();
19350        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19351                true /* requireFullPermission */, false /* checkShell */,
19352                "replace preferred activity");
19353        synchronized (mPackages) {
19354            if (mContext.checkCallingOrSelfPermission(
19355                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19356                    != PackageManager.PERMISSION_GRANTED) {
19357                if (getUidTargetSdkVersionLockedLPr(callingUid)
19358                        < Build.VERSION_CODES.FROYO) {
19359                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19360                            + Binder.getCallingUid());
19361                    return;
19362                }
19363                mContext.enforceCallingOrSelfPermission(
19364                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19365            }
19366
19367            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19368            if (pir != null) {
19369                // Get all of the existing entries that exactly match this filter.
19370                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19371                if (existing != null && existing.size() == 1) {
19372                    PreferredActivity cur = existing.get(0);
19373                    if (DEBUG_PREFERRED) {
19374                        Slog.i(TAG, "Checking replace of preferred:");
19375                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19376                        if (!cur.mPref.mAlways) {
19377                            Slog.i(TAG, "  -- CUR; not mAlways!");
19378                        } else {
19379                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19380                            Slog.i(TAG, "  -- CUR: mSet="
19381                                    + Arrays.toString(cur.mPref.mSetComponents));
19382                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19383                            Slog.i(TAG, "  -- NEW: mMatch="
19384                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19385                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19386                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19387                        }
19388                    }
19389                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19390                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19391                            && cur.mPref.sameSet(set)) {
19392                        // Setting the preferred activity to what it happens to be already
19393                        if (DEBUG_PREFERRED) {
19394                            Slog.i(TAG, "Replacing with same preferred activity "
19395                                    + cur.mPref.mShortComponent + " for user "
19396                                    + userId + ":");
19397                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19398                        }
19399                        return;
19400                    }
19401                }
19402
19403                if (existing != null) {
19404                    if (DEBUG_PREFERRED) {
19405                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19406                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19407                    }
19408                    for (int i = 0; i < existing.size(); i++) {
19409                        PreferredActivity pa = existing.get(i);
19410                        if (DEBUG_PREFERRED) {
19411                            Slog.i(TAG, "Removing existing preferred activity "
19412                                    + pa.mPref.mComponent + ":");
19413                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19414                        }
19415                        pir.removeFilter(pa);
19416                    }
19417                }
19418            }
19419            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19420                    "Replacing preferred");
19421        }
19422    }
19423
19424    @Override
19425    public void clearPackagePreferredActivities(String packageName) {
19426        final int callingUid = Binder.getCallingUid();
19427        if (getInstantAppPackageName(callingUid) != null) {
19428            return;
19429        }
19430        // writer
19431        synchronized (mPackages) {
19432            PackageParser.Package pkg = mPackages.get(packageName);
19433            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
19434                if (mContext.checkCallingOrSelfPermission(
19435                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19436                        != PackageManager.PERMISSION_GRANTED) {
19437                    if (getUidTargetSdkVersionLockedLPr(callingUid)
19438                            < Build.VERSION_CODES.FROYO) {
19439                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19440                                + callingUid);
19441                        return;
19442                    }
19443                    mContext.enforceCallingOrSelfPermission(
19444                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19445                }
19446            }
19447            final PackageSetting ps = mSettings.getPackageLPr(packageName);
19448            if (ps != null
19449                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
19450                return;
19451            }
19452            int user = UserHandle.getCallingUserId();
19453            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19454                scheduleWritePackageRestrictionsLocked(user);
19455            }
19456        }
19457    }
19458
19459    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19460    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19461        ArrayList<PreferredActivity> removed = null;
19462        boolean changed = false;
19463        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19464            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19465            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19466            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19467                continue;
19468            }
19469            Iterator<PreferredActivity> it = pir.filterIterator();
19470            while (it.hasNext()) {
19471                PreferredActivity pa = it.next();
19472                // Mark entry for removal only if it matches the package name
19473                // and the entry is of type "always".
19474                if (packageName == null ||
19475                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19476                                && pa.mPref.mAlways)) {
19477                    if (removed == null) {
19478                        removed = new ArrayList<PreferredActivity>();
19479                    }
19480                    removed.add(pa);
19481                }
19482            }
19483            if (removed != null) {
19484                for (int j=0; j<removed.size(); j++) {
19485                    PreferredActivity pa = removed.get(j);
19486                    pir.removeFilter(pa);
19487                }
19488                changed = true;
19489            }
19490        }
19491        if (changed) {
19492            postPreferredActivityChangedBroadcast(userId);
19493        }
19494        return changed;
19495    }
19496
19497    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19498    private void clearIntentFilterVerificationsLPw(int userId) {
19499        final int packageCount = mPackages.size();
19500        for (int i = 0; i < packageCount; i++) {
19501            PackageParser.Package pkg = mPackages.valueAt(i);
19502            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19503        }
19504    }
19505
19506    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19507    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19508        if (userId == UserHandle.USER_ALL) {
19509            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19510                    sUserManager.getUserIds())) {
19511                for (int oneUserId : sUserManager.getUserIds()) {
19512                    scheduleWritePackageRestrictionsLocked(oneUserId);
19513                }
19514            }
19515        } else {
19516            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19517                scheduleWritePackageRestrictionsLocked(userId);
19518            }
19519        }
19520    }
19521
19522    /** Clears state for all users, and touches intent filter verification policy */
19523    void clearDefaultBrowserIfNeeded(String packageName) {
19524        for (int oneUserId : sUserManager.getUserIds()) {
19525            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19526        }
19527    }
19528
19529    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19530        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19531        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19532            if (packageName.equals(defaultBrowserPackageName)) {
19533                setDefaultBrowserPackageName(null, userId);
19534            }
19535        }
19536    }
19537
19538    @Override
19539    public void resetApplicationPreferences(int userId) {
19540        mContext.enforceCallingOrSelfPermission(
19541                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19542        final long identity = Binder.clearCallingIdentity();
19543        // writer
19544        try {
19545            synchronized (mPackages) {
19546                clearPackagePreferredActivitiesLPw(null, userId);
19547                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19548                // TODO: We have to reset the default SMS and Phone. This requires
19549                // significant refactoring to keep all default apps in the package
19550                // manager (cleaner but more work) or have the services provide
19551                // callbacks to the package manager to request a default app reset.
19552                applyFactoryDefaultBrowserLPw(userId);
19553                clearIntentFilterVerificationsLPw(userId);
19554                primeDomainVerificationsLPw(userId);
19555                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19556                scheduleWritePackageRestrictionsLocked(userId);
19557            }
19558            resetNetworkPolicies(userId);
19559        } finally {
19560            Binder.restoreCallingIdentity(identity);
19561        }
19562    }
19563
19564    @Override
19565    public int getPreferredActivities(List<IntentFilter> outFilters,
19566            List<ComponentName> outActivities, String packageName) {
19567        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19568            return 0;
19569        }
19570        int num = 0;
19571        final int userId = UserHandle.getCallingUserId();
19572        // reader
19573        synchronized (mPackages) {
19574            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19575            if (pir != null) {
19576                final Iterator<PreferredActivity> it = pir.filterIterator();
19577                while (it.hasNext()) {
19578                    final PreferredActivity pa = it.next();
19579                    if (packageName == null
19580                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19581                                    && pa.mPref.mAlways)) {
19582                        if (outFilters != null) {
19583                            outFilters.add(new IntentFilter(pa));
19584                        }
19585                        if (outActivities != null) {
19586                            outActivities.add(pa.mPref.mComponent);
19587                        }
19588                    }
19589                }
19590            }
19591        }
19592
19593        return num;
19594    }
19595
19596    @Override
19597    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19598            int userId) {
19599        int callingUid = Binder.getCallingUid();
19600        if (callingUid != Process.SYSTEM_UID) {
19601            throw new SecurityException(
19602                    "addPersistentPreferredActivity can only be run by the system");
19603        }
19604        if (filter.countActions() == 0) {
19605            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19606            return;
19607        }
19608        synchronized (mPackages) {
19609            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19610                    ":");
19611            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19612            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19613                    new PersistentPreferredActivity(filter, activity));
19614            scheduleWritePackageRestrictionsLocked(userId);
19615            postPreferredActivityChangedBroadcast(userId);
19616        }
19617    }
19618
19619    @Override
19620    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19621        int callingUid = Binder.getCallingUid();
19622        if (callingUid != Process.SYSTEM_UID) {
19623            throw new SecurityException(
19624                    "clearPackagePersistentPreferredActivities can only be run by the system");
19625        }
19626        ArrayList<PersistentPreferredActivity> removed = null;
19627        boolean changed = false;
19628        synchronized (mPackages) {
19629            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19630                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19631                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19632                        .valueAt(i);
19633                if (userId != thisUserId) {
19634                    continue;
19635                }
19636                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19637                while (it.hasNext()) {
19638                    PersistentPreferredActivity ppa = it.next();
19639                    // Mark entry for removal only if it matches the package name.
19640                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19641                        if (removed == null) {
19642                            removed = new ArrayList<PersistentPreferredActivity>();
19643                        }
19644                        removed.add(ppa);
19645                    }
19646                }
19647                if (removed != null) {
19648                    for (int j=0; j<removed.size(); j++) {
19649                        PersistentPreferredActivity ppa = removed.get(j);
19650                        ppir.removeFilter(ppa);
19651                    }
19652                    changed = true;
19653                }
19654            }
19655
19656            if (changed) {
19657                scheduleWritePackageRestrictionsLocked(userId);
19658                postPreferredActivityChangedBroadcast(userId);
19659            }
19660        }
19661    }
19662
19663    /**
19664     * Common machinery for picking apart a restored XML blob and passing
19665     * it to a caller-supplied functor to be applied to the running system.
19666     */
19667    private void restoreFromXml(XmlPullParser parser, int userId,
19668            String expectedStartTag, BlobXmlRestorer functor)
19669            throws IOException, XmlPullParserException {
19670        int type;
19671        while ((type = parser.next()) != XmlPullParser.START_TAG
19672                && type != XmlPullParser.END_DOCUMENT) {
19673        }
19674        if (type != XmlPullParser.START_TAG) {
19675            // oops didn't find a start tag?!
19676            if (DEBUG_BACKUP) {
19677                Slog.e(TAG, "Didn't find start tag during restore");
19678            }
19679            return;
19680        }
19681Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19682        // this is supposed to be TAG_PREFERRED_BACKUP
19683        if (!expectedStartTag.equals(parser.getName())) {
19684            if (DEBUG_BACKUP) {
19685                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19686            }
19687            return;
19688        }
19689
19690        // skip interfering stuff, then we're aligned with the backing implementation
19691        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19692Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19693        functor.apply(parser, userId);
19694    }
19695
19696    private interface BlobXmlRestorer {
19697        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19698    }
19699
19700    /**
19701     * Non-Binder method, support for the backup/restore mechanism: write the
19702     * full set of preferred activities in its canonical XML format.  Returns the
19703     * XML output as a byte array, or null if there is none.
19704     */
19705    @Override
19706    public byte[] getPreferredActivityBackup(int userId) {
19707        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19708            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19709        }
19710
19711        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19712        try {
19713            final XmlSerializer serializer = new FastXmlSerializer();
19714            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19715            serializer.startDocument(null, true);
19716            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19717
19718            synchronized (mPackages) {
19719                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19720            }
19721
19722            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19723            serializer.endDocument();
19724            serializer.flush();
19725        } catch (Exception e) {
19726            if (DEBUG_BACKUP) {
19727                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19728            }
19729            return null;
19730        }
19731
19732        return dataStream.toByteArray();
19733    }
19734
19735    @Override
19736    public void restorePreferredActivities(byte[] backup, int userId) {
19737        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19738            throw new SecurityException("Only the system may call restorePreferredActivities()");
19739        }
19740
19741        try {
19742            final XmlPullParser parser = Xml.newPullParser();
19743            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19744            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19745                    new BlobXmlRestorer() {
19746                        @Override
19747                        public void apply(XmlPullParser parser, int userId)
19748                                throws XmlPullParserException, IOException {
19749                            synchronized (mPackages) {
19750                                mSettings.readPreferredActivitiesLPw(parser, userId);
19751                            }
19752                        }
19753                    } );
19754        } catch (Exception e) {
19755            if (DEBUG_BACKUP) {
19756                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19757            }
19758        }
19759    }
19760
19761    /**
19762     * Non-Binder method, support for the backup/restore mechanism: write the
19763     * default browser (etc) settings in its canonical XML format.  Returns the default
19764     * browser XML representation as a byte array, or null if there is none.
19765     */
19766    @Override
19767    public byte[] getDefaultAppsBackup(int userId) {
19768        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19769            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19770        }
19771
19772        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19773        try {
19774            final XmlSerializer serializer = new FastXmlSerializer();
19775            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19776            serializer.startDocument(null, true);
19777            serializer.startTag(null, TAG_DEFAULT_APPS);
19778
19779            synchronized (mPackages) {
19780                mSettings.writeDefaultAppsLPr(serializer, userId);
19781            }
19782
19783            serializer.endTag(null, TAG_DEFAULT_APPS);
19784            serializer.endDocument();
19785            serializer.flush();
19786        } catch (Exception e) {
19787            if (DEBUG_BACKUP) {
19788                Slog.e(TAG, "Unable to write default apps for backup", e);
19789            }
19790            return null;
19791        }
19792
19793        return dataStream.toByteArray();
19794    }
19795
19796    @Override
19797    public void restoreDefaultApps(byte[] backup, int userId) {
19798        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19799            throw new SecurityException("Only the system may call restoreDefaultApps()");
19800        }
19801
19802        try {
19803            final XmlPullParser parser = Xml.newPullParser();
19804            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19805            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19806                    new BlobXmlRestorer() {
19807                        @Override
19808                        public void apply(XmlPullParser parser, int userId)
19809                                throws XmlPullParserException, IOException {
19810                            synchronized (mPackages) {
19811                                mSettings.readDefaultAppsLPw(parser, userId);
19812                            }
19813                        }
19814                    } );
19815        } catch (Exception e) {
19816            if (DEBUG_BACKUP) {
19817                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19818            }
19819        }
19820    }
19821
19822    @Override
19823    public byte[] getIntentFilterVerificationBackup(int userId) {
19824        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19825            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19826        }
19827
19828        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19829        try {
19830            final XmlSerializer serializer = new FastXmlSerializer();
19831            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19832            serializer.startDocument(null, true);
19833            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19834
19835            synchronized (mPackages) {
19836                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19837            }
19838
19839            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19840            serializer.endDocument();
19841            serializer.flush();
19842        } catch (Exception e) {
19843            if (DEBUG_BACKUP) {
19844                Slog.e(TAG, "Unable to write default apps for backup", e);
19845            }
19846            return null;
19847        }
19848
19849        return dataStream.toByteArray();
19850    }
19851
19852    @Override
19853    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19854        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19855            throw new SecurityException("Only the system may call restorePreferredActivities()");
19856        }
19857
19858        try {
19859            final XmlPullParser parser = Xml.newPullParser();
19860            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19861            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19862                    new BlobXmlRestorer() {
19863                        @Override
19864                        public void apply(XmlPullParser parser, int userId)
19865                                throws XmlPullParserException, IOException {
19866                            synchronized (mPackages) {
19867                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19868                                mSettings.writeLPr();
19869                            }
19870                        }
19871                    } );
19872        } catch (Exception e) {
19873            if (DEBUG_BACKUP) {
19874                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19875            }
19876        }
19877    }
19878
19879    @Override
19880    public byte[] getPermissionGrantBackup(int userId) {
19881        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19882            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19883        }
19884
19885        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19886        try {
19887            final XmlSerializer serializer = new FastXmlSerializer();
19888            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19889            serializer.startDocument(null, true);
19890            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19891
19892            synchronized (mPackages) {
19893                serializeRuntimePermissionGrantsLPr(serializer, userId);
19894            }
19895
19896            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19897            serializer.endDocument();
19898            serializer.flush();
19899        } catch (Exception e) {
19900            if (DEBUG_BACKUP) {
19901                Slog.e(TAG, "Unable to write default apps for backup", e);
19902            }
19903            return null;
19904        }
19905
19906        return dataStream.toByteArray();
19907    }
19908
19909    @Override
19910    public void restorePermissionGrants(byte[] backup, int userId) {
19911        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19912            throw new SecurityException("Only the system may call restorePermissionGrants()");
19913        }
19914
19915        try {
19916            final XmlPullParser parser = Xml.newPullParser();
19917            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19918            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19919                    new BlobXmlRestorer() {
19920                        @Override
19921                        public void apply(XmlPullParser parser, int userId)
19922                                throws XmlPullParserException, IOException {
19923                            synchronized (mPackages) {
19924                                processRestoredPermissionGrantsLPr(parser, userId);
19925                            }
19926                        }
19927                    } );
19928        } catch (Exception e) {
19929            if (DEBUG_BACKUP) {
19930                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19931            }
19932        }
19933    }
19934
19935    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19936            throws IOException {
19937        serializer.startTag(null, TAG_ALL_GRANTS);
19938
19939        final int N = mSettings.mPackages.size();
19940        for (int i = 0; i < N; i++) {
19941            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19942            boolean pkgGrantsKnown = false;
19943
19944            PermissionsState packagePerms = ps.getPermissionsState();
19945
19946            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19947                final int grantFlags = state.getFlags();
19948                // only look at grants that are not system/policy fixed
19949                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19950                    final boolean isGranted = state.isGranted();
19951                    // And only back up the user-twiddled state bits
19952                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19953                        final String packageName = mSettings.mPackages.keyAt(i);
19954                        if (!pkgGrantsKnown) {
19955                            serializer.startTag(null, TAG_GRANT);
19956                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19957                            pkgGrantsKnown = true;
19958                        }
19959
19960                        final boolean userSet =
19961                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19962                        final boolean userFixed =
19963                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19964                        final boolean revoke =
19965                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19966
19967                        serializer.startTag(null, TAG_PERMISSION);
19968                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19969                        if (isGranted) {
19970                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19971                        }
19972                        if (userSet) {
19973                            serializer.attribute(null, ATTR_USER_SET, "true");
19974                        }
19975                        if (userFixed) {
19976                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19977                        }
19978                        if (revoke) {
19979                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19980                        }
19981                        serializer.endTag(null, TAG_PERMISSION);
19982                    }
19983                }
19984            }
19985
19986            if (pkgGrantsKnown) {
19987                serializer.endTag(null, TAG_GRANT);
19988            }
19989        }
19990
19991        serializer.endTag(null, TAG_ALL_GRANTS);
19992    }
19993
19994    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19995            throws XmlPullParserException, IOException {
19996        String pkgName = null;
19997        int outerDepth = parser.getDepth();
19998        int type;
19999        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20000                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20001            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20002                continue;
20003            }
20004
20005            final String tagName = parser.getName();
20006            if (tagName.equals(TAG_GRANT)) {
20007                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20008                if (DEBUG_BACKUP) {
20009                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20010                }
20011            } else if (tagName.equals(TAG_PERMISSION)) {
20012
20013                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20014                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20015
20016                int newFlagSet = 0;
20017                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20018                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20019                }
20020                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20021                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20022                }
20023                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20024                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20025                }
20026                if (DEBUG_BACKUP) {
20027                    Slog.v(TAG, "  + Restoring grant:"
20028                            + " pkg=" + pkgName
20029                            + " perm=" + permName
20030                            + " granted=" + isGranted
20031                            + " bits=0x" + Integer.toHexString(newFlagSet));
20032                }
20033                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20034                if (ps != null) {
20035                    // Already installed so we apply the grant immediately
20036                    if (DEBUG_BACKUP) {
20037                        Slog.v(TAG, "        + already installed; applying");
20038                    }
20039                    PermissionsState perms = ps.getPermissionsState();
20040                    BasePermission bp =
20041                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
20042                    if (bp != null) {
20043                        if (isGranted) {
20044                            perms.grantRuntimePermission(bp, userId);
20045                        }
20046                        if (newFlagSet != 0) {
20047                            perms.updatePermissionFlags(
20048                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20049                        }
20050                    }
20051                } else {
20052                    // Need to wait for post-restore install to apply the grant
20053                    if (DEBUG_BACKUP) {
20054                        Slog.v(TAG, "        - not yet installed; saving for later");
20055                    }
20056                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20057                            isGranted, newFlagSet, userId);
20058                }
20059            } else {
20060                PackageManagerService.reportSettingsProblem(Log.WARN,
20061                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20062                XmlUtils.skipCurrentTag(parser);
20063            }
20064        }
20065
20066        scheduleWriteSettingsLocked();
20067        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20068    }
20069
20070    @Override
20071    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20072            int sourceUserId, int targetUserId, int flags) {
20073        mContext.enforceCallingOrSelfPermission(
20074                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20075        int callingUid = Binder.getCallingUid();
20076        enforceOwnerRights(ownerPackage, callingUid);
20077        PackageManagerServiceUtils.enforceShellRestriction(
20078                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20079        if (intentFilter.countActions() == 0) {
20080            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20081            return;
20082        }
20083        synchronized (mPackages) {
20084            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20085                    ownerPackage, targetUserId, flags);
20086            CrossProfileIntentResolver resolver =
20087                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20088            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20089            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20090            if (existing != null) {
20091                int size = existing.size();
20092                for (int i = 0; i < size; i++) {
20093                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20094                        return;
20095                    }
20096                }
20097            }
20098            resolver.addFilter(newFilter);
20099            scheduleWritePackageRestrictionsLocked(sourceUserId);
20100        }
20101    }
20102
20103    @Override
20104    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20105        mContext.enforceCallingOrSelfPermission(
20106                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20107        final int callingUid = Binder.getCallingUid();
20108        enforceOwnerRights(ownerPackage, callingUid);
20109        PackageManagerServiceUtils.enforceShellRestriction(
20110                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20111        synchronized (mPackages) {
20112            CrossProfileIntentResolver resolver =
20113                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20114            ArraySet<CrossProfileIntentFilter> set =
20115                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20116            for (CrossProfileIntentFilter filter : set) {
20117                if (filter.getOwnerPackage().equals(ownerPackage)) {
20118                    resolver.removeFilter(filter);
20119                }
20120            }
20121            scheduleWritePackageRestrictionsLocked(sourceUserId);
20122        }
20123    }
20124
20125    // Enforcing that callingUid is owning pkg on userId
20126    private void enforceOwnerRights(String pkg, int callingUid) {
20127        // The system owns everything.
20128        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20129            return;
20130        }
20131        final int callingUserId = UserHandle.getUserId(callingUid);
20132        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20133        if (pi == null) {
20134            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20135                    + callingUserId);
20136        }
20137        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20138            throw new SecurityException("Calling uid " + callingUid
20139                    + " does not own package " + pkg);
20140        }
20141    }
20142
20143    @Override
20144    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20145        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20146            return null;
20147        }
20148        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20149    }
20150
20151    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20152        UserManagerService ums = UserManagerService.getInstance();
20153        if (ums != null) {
20154            final UserInfo parent = ums.getProfileParent(userId);
20155            final int launcherUid = (parent != null) ? parent.id : userId;
20156            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20157            if (launcherComponent != null) {
20158                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20159                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20160                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20161                        .setPackage(launcherComponent.getPackageName());
20162                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20163            }
20164        }
20165    }
20166
20167    /**
20168     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20169     * then reports the most likely home activity or null if there are more than one.
20170     */
20171    private ComponentName getDefaultHomeActivity(int userId) {
20172        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20173        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20174        if (cn != null) {
20175            return cn;
20176        }
20177
20178        // Find the launcher with the highest priority and return that component if there are no
20179        // other home activity with the same priority.
20180        int lastPriority = Integer.MIN_VALUE;
20181        ComponentName lastComponent = null;
20182        final int size = allHomeCandidates.size();
20183        for (int i = 0; i < size; i++) {
20184            final ResolveInfo ri = allHomeCandidates.get(i);
20185            if (ri.priority > lastPriority) {
20186                lastComponent = ri.activityInfo.getComponentName();
20187                lastPriority = ri.priority;
20188            } else if (ri.priority == lastPriority) {
20189                // Two components found with same priority.
20190                lastComponent = null;
20191            }
20192        }
20193        return lastComponent;
20194    }
20195
20196    private Intent getHomeIntent() {
20197        Intent intent = new Intent(Intent.ACTION_MAIN);
20198        intent.addCategory(Intent.CATEGORY_HOME);
20199        intent.addCategory(Intent.CATEGORY_DEFAULT);
20200        return intent;
20201    }
20202
20203    private IntentFilter getHomeFilter() {
20204        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20205        filter.addCategory(Intent.CATEGORY_HOME);
20206        filter.addCategory(Intent.CATEGORY_DEFAULT);
20207        return filter;
20208    }
20209
20210    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20211            int userId) {
20212        Intent intent  = getHomeIntent();
20213        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20214                PackageManager.GET_META_DATA, userId);
20215        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20216                true, false, false, userId);
20217
20218        allHomeCandidates.clear();
20219        if (list != null) {
20220            for (ResolveInfo ri : list) {
20221                allHomeCandidates.add(ri);
20222            }
20223        }
20224        return (preferred == null || preferred.activityInfo == null)
20225                ? null
20226                : new ComponentName(preferred.activityInfo.packageName,
20227                        preferred.activityInfo.name);
20228    }
20229
20230    @Override
20231    public void setHomeActivity(ComponentName comp, int userId) {
20232        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20233            return;
20234        }
20235        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20236        getHomeActivitiesAsUser(homeActivities, userId);
20237
20238        boolean found = false;
20239
20240        final int size = homeActivities.size();
20241        final ComponentName[] set = new ComponentName[size];
20242        for (int i = 0; i < size; i++) {
20243            final ResolveInfo candidate = homeActivities.get(i);
20244            final ActivityInfo info = candidate.activityInfo;
20245            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20246            set[i] = activityName;
20247            if (!found && activityName.equals(comp)) {
20248                found = true;
20249            }
20250        }
20251        if (!found) {
20252            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20253                    + userId);
20254        }
20255        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20256                set, comp, userId);
20257    }
20258
20259    private @Nullable String getSetupWizardPackageName() {
20260        final Intent intent = new Intent(Intent.ACTION_MAIN);
20261        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20262
20263        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20264                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20265                        | MATCH_DISABLED_COMPONENTS,
20266                UserHandle.myUserId());
20267        if (matches.size() == 1) {
20268            return matches.get(0).getComponentInfo().packageName;
20269        } else {
20270            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20271                    + ": matches=" + matches);
20272            return null;
20273        }
20274    }
20275
20276    private @Nullable String getStorageManagerPackageName() {
20277        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20278
20279        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20280                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20281                        | MATCH_DISABLED_COMPONENTS,
20282                UserHandle.myUserId());
20283        if (matches.size() == 1) {
20284            return matches.get(0).getComponentInfo().packageName;
20285        } else {
20286            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20287                    + matches.size() + ": matches=" + matches);
20288            return null;
20289        }
20290    }
20291
20292    @Override
20293    public void setApplicationEnabledSetting(String appPackageName,
20294            int newState, int flags, int userId, String callingPackage) {
20295        if (!sUserManager.exists(userId)) return;
20296        if (callingPackage == null) {
20297            callingPackage = Integer.toString(Binder.getCallingUid());
20298        }
20299        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20300    }
20301
20302    @Override
20303    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20304        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20305        synchronized (mPackages) {
20306            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20307            if (pkgSetting != null) {
20308                pkgSetting.setUpdateAvailable(updateAvailable);
20309            }
20310        }
20311    }
20312
20313    @Override
20314    public void setComponentEnabledSetting(ComponentName componentName,
20315            int newState, int flags, int userId) {
20316        if (!sUserManager.exists(userId)) return;
20317        setEnabledSetting(componentName.getPackageName(),
20318                componentName.getClassName(), newState, flags, userId, null);
20319    }
20320
20321    private void setEnabledSetting(final String packageName, String className, int newState,
20322            final int flags, int userId, String callingPackage) {
20323        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20324              || newState == COMPONENT_ENABLED_STATE_ENABLED
20325              || newState == COMPONENT_ENABLED_STATE_DISABLED
20326              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20327              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20328            throw new IllegalArgumentException("Invalid new component state: "
20329                    + newState);
20330        }
20331        PackageSetting pkgSetting;
20332        final int callingUid = Binder.getCallingUid();
20333        final int permission;
20334        if (callingUid == Process.SYSTEM_UID) {
20335            permission = PackageManager.PERMISSION_GRANTED;
20336        } else {
20337            permission = mContext.checkCallingOrSelfPermission(
20338                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20339        }
20340        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20341                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20342        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20343        boolean sendNow = false;
20344        boolean isApp = (className == null);
20345        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
20346        String componentName = isApp ? packageName : className;
20347        int packageUid = -1;
20348        ArrayList<String> components;
20349
20350        // reader
20351        synchronized (mPackages) {
20352            pkgSetting = mSettings.mPackages.get(packageName);
20353            if (pkgSetting == null) {
20354                if (!isCallerInstantApp) {
20355                    if (className == null) {
20356                        throw new IllegalArgumentException("Unknown package: " + packageName);
20357                    }
20358                    throw new IllegalArgumentException(
20359                            "Unknown component: " + packageName + "/" + className);
20360                } else {
20361                    // throw SecurityException to prevent leaking package information
20362                    throw new SecurityException(
20363                            "Attempt to change component state; "
20364                            + "pid=" + Binder.getCallingPid()
20365                            + ", uid=" + callingUid
20366                            + (className == null
20367                                    ? ", package=" + packageName
20368                                    : ", component=" + packageName + "/" + className));
20369                }
20370            }
20371        }
20372
20373        // Limit who can change which apps
20374        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
20375            // Don't allow apps that don't have permission to modify other apps
20376            if (!allowedByPermission
20377                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
20378                throw new SecurityException(
20379                        "Attempt to change component state; "
20380                        + "pid=" + Binder.getCallingPid()
20381                        + ", uid=" + callingUid
20382                        + (className == null
20383                                ? ", package=" + packageName
20384                                : ", component=" + packageName + "/" + className));
20385            }
20386            // Don't allow changing protected packages.
20387            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20388                throw new SecurityException("Cannot disable a protected package: " + packageName);
20389            }
20390        }
20391
20392        synchronized (mPackages) {
20393            if (callingUid == Process.SHELL_UID
20394                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20395                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20396                // unless it is a test package.
20397                int oldState = pkgSetting.getEnabled(userId);
20398                if (className == null
20399                        &&
20400                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20401                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20402                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20403                        &&
20404                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20405                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
20406                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20407                    // ok
20408                } else {
20409                    throw new SecurityException(
20410                            "Shell cannot change component state for " + packageName + "/"
20411                                    + className + " to " + newState);
20412                }
20413            }
20414        }
20415        if (className == null) {
20416            // We're dealing with an application/package level state change
20417            synchronized (mPackages) {
20418                if (pkgSetting.getEnabled(userId) == newState) {
20419                    // Nothing to do
20420                    return;
20421                }
20422            }
20423            // If we're enabling a system stub, there's a little more work to do.
20424            // Prior to enabling the package, we need to decompress the APK(s) to the
20425            // data partition and then replace the version on the system partition.
20426            final PackageParser.Package deletedPkg = pkgSetting.pkg;
20427            final boolean isSystemStub = deletedPkg.isStub
20428                    && deletedPkg.isSystem();
20429            if (isSystemStub
20430                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20431                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
20432                final File codePath = decompressPackage(deletedPkg);
20433                if (codePath == null) {
20434                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
20435                    return;
20436                }
20437                // TODO remove direct parsing of the package object during internal cleanup
20438                // of scan package
20439                // We need to call parse directly here for no other reason than we need
20440                // the new package in order to disable the old one [we use the information
20441                // for some internal optimization to optionally create a new package setting
20442                // object on replace]. However, we can't get the package from the scan
20443                // because the scan modifies live structures and we need to remove the
20444                // old [system] package from the system before a scan can be attempted.
20445                // Once scan is indempotent we can remove this parse and use the package
20446                // object we scanned, prior to adding it to package settings.
20447                final PackageParser pp = new PackageParser();
20448                pp.setSeparateProcesses(mSeparateProcesses);
20449                pp.setDisplayMetrics(mMetrics);
20450                pp.setCallback(mPackageParserCallback);
20451                final PackageParser.Package tmpPkg;
20452                try {
20453                    final @ParseFlags int parseFlags = mDefParseFlags
20454                            | PackageParser.PARSE_MUST_BE_APK
20455                            | PackageParser.PARSE_IS_SYSTEM_DIR;
20456                    tmpPkg = pp.parsePackage(codePath, parseFlags);
20457                } catch (PackageParserException e) {
20458                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
20459                    return;
20460                }
20461                synchronized (mInstallLock) {
20462                    // Disable the stub and remove any package entries
20463                    removePackageLI(deletedPkg, true);
20464                    synchronized (mPackages) {
20465                        disableSystemPackageLPw(deletedPkg, tmpPkg);
20466                    }
20467                    final PackageParser.Package pkg;
20468                    try (PackageFreezer freezer =
20469                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20470                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
20471                                | PackageParser.PARSE_ENFORCE_CODE;
20472                        pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
20473                                0 /*currentTime*/, null /*user*/);
20474                        prepareAppDataAfterInstallLIF(pkg);
20475                        synchronized (mPackages) {
20476                            try {
20477                                updateSharedLibrariesLPr(pkg, null);
20478                            } catch (PackageManagerException e) {
20479                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
20480                            }
20481                            mPermissionManager.updatePermissions(
20482                                    pkg.packageName, pkg, true, mPackages.values(),
20483                                    mPermissionCallback);
20484                            mSettings.writeLPr();
20485                        }
20486                    } catch (PackageManagerException e) {
20487                        // Whoops! Something went wrong; try to roll back to the stub
20488                        Slog.w(TAG, "Failed to install compressed system package:"
20489                                + pkgSetting.name, e);
20490                        // Remove the failed install
20491                        removeCodePathLI(codePath);
20492
20493                        // Install the system package
20494                        try (PackageFreezer freezer =
20495                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20496                            synchronized (mPackages) {
20497                                // NOTE: The system package always needs to be enabled; even
20498                                // if it's for a compressed stub. If we don't, installing the
20499                                // system package fails during scan [scanning checks the disabled
20500                                // packages]. We will reverse this later, after we've "installed"
20501                                // the stub.
20502                                // This leaves us in a fragile state; the stub should never be
20503                                // enabled, so, cross your fingers and hope nothing goes wrong
20504                                // until we can disable the package later.
20505                                enableSystemPackageLPw(deletedPkg);
20506                            }
20507                            installPackageFromSystemLIF(deletedPkg.codePath,
20508                                    false /*isPrivileged*/, null /*allUserHandles*/,
20509                                    null /*origUserHandles*/, null /*origPermissionsState*/,
20510                                    true /*writeSettings*/);
20511                        } catch (PackageManagerException pme) {
20512                            Slog.w(TAG, "Failed to restore system package:"
20513                                    + deletedPkg.packageName, pme);
20514                        } finally {
20515                            synchronized (mPackages) {
20516                                mSettings.disableSystemPackageLPw(
20517                                        deletedPkg.packageName, true /*replaced*/);
20518                                mSettings.writeLPr();
20519                            }
20520                        }
20521                        return;
20522                    }
20523                    clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
20524                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20525                    mDexManager.notifyPackageUpdated(pkg.packageName,
20526                            pkg.baseCodePath, pkg.splitCodePaths);
20527                }
20528            }
20529            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20530                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20531                // Don't care about who enables an app.
20532                callingPackage = null;
20533            }
20534            synchronized (mPackages) {
20535                pkgSetting.setEnabled(newState, userId, callingPackage);
20536            }
20537        } else {
20538            synchronized (mPackages) {
20539                // We're dealing with a component level state change
20540                // First, verify that this is a valid class name.
20541                PackageParser.Package pkg = pkgSetting.pkg;
20542                if (pkg == null || !pkg.hasComponentClassName(className)) {
20543                    if (pkg != null &&
20544                            pkg.applicationInfo.targetSdkVersion >=
20545                                    Build.VERSION_CODES.JELLY_BEAN) {
20546                        throw new IllegalArgumentException("Component class " + className
20547                                + " does not exist in " + packageName);
20548                    } else {
20549                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20550                                + className + " does not exist in " + packageName);
20551                    }
20552                }
20553                switch (newState) {
20554                    case COMPONENT_ENABLED_STATE_ENABLED:
20555                        if (!pkgSetting.enableComponentLPw(className, userId)) {
20556                            return;
20557                        }
20558                        break;
20559                    case COMPONENT_ENABLED_STATE_DISABLED:
20560                        if (!pkgSetting.disableComponentLPw(className, userId)) {
20561                            return;
20562                        }
20563                        break;
20564                    case COMPONENT_ENABLED_STATE_DEFAULT:
20565                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
20566                            return;
20567                        }
20568                        break;
20569                    default:
20570                        Slog.e(TAG, "Invalid new component state: " + newState);
20571                        return;
20572                }
20573            }
20574        }
20575        synchronized (mPackages) {
20576            scheduleWritePackageRestrictionsLocked(userId);
20577            updateSequenceNumberLP(pkgSetting, new int[] { userId });
20578            final long callingId = Binder.clearCallingIdentity();
20579            try {
20580                updateInstantAppInstallerLocked(packageName);
20581            } finally {
20582                Binder.restoreCallingIdentity(callingId);
20583            }
20584            components = mPendingBroadcasts.get(userId, packageName);
20585            final boolean newPackage = components == null;
20586            if (newPackage) {
20587                components = new ArrayList<String>();
20588            }
20589            if (!components.contains(componentName)) {
20590                components.add(componentName);
20591            }
20592            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20593                sendNow = true;
20594                // Purge entry from pending broadcast list if another one exists already
20595                // since we are sending one right away.
20596                mPendingBroadcasts.remove(userId, packageName);
20597            } else {
20598                if (newPackage) {
20599                    mPendingBroadcasts.put(userId, packageName, components);
20600                }
20601                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20602                    // Schedule a message
20603                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20604                }
20605            }
20606        }
20607
20608        long callingId = Binder.clearCallingIdentity();
20609        try {
20610            if (sendNow) {
20611                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20612                sendPackageChangedBroadcast(packageName,
20613                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20614            }
20615        } finally {
20616            Binder.restoreCallingIdentity(callingId);
20617        }
20618    }
20619
20620    @Override
20621    public void flushPackageRestrictionsAsUser(int userId) {
20622        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20623            return;
20624        }
20625        if (!sUserManager.exists(userId)) {
20626            return;
20627        }
20628        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20629                false /* checkShell */, "flushPackageRestrictions");
20630        synchronized (mPackages) {
20631            mSettings.writePackageRestrictionsLPr(userId);
20632            mDirtyUsers.remove(userId);
20633            if (mDirtyUsers.isEmpty()) {
20634                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20635            }
20636        }
20637    }
20638
20639    private void sendPackageChangedBroadcast(String packageName,
20640            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20641        if (DEBUG_INSTALL)
20642            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20643                    + componentNames);
20644        Bundle extras = new Bundle(4);
20645        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20646        String nameList[] = new String[componentNames.size()];
20647        componentNames.toArray(nameList);
20648        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20649        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20650        extras.putInt(Intent.EXTRA_UID, packageUid);
20651        // If this is not reporting a change of the overall package, then only send it
20652        // to registered receivers.  We don't want to launch a swath of apps for every
20653        // little component state change.
20654        final int flags = !componentNames.contains(packageName)
20655                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20656        final int userId = UserHandle.getUserId(packageUid);
20657        final boolean isInstantApp = isInstantApp(packageName, userId);
20658        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
20659        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
20660        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20661                userIds, instantUserIds);
20662    }
20663
20664    @Override
20665    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20666        if (!sUserManager.exists(userId)) return;
20667        final int callingUid = Binder.getCallingUid();
20668        if (getInstantAppPackageName(callingUid) != null) {
20669            return;
20670        }
20671        final int permission = mContext.checkCallingOrSelfPermission(
20672                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20673        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20674        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20675                true /* requireFullPermission */, true /* checkShell */, "stop package");
20676        // writer
20677        synchronized (mPackages) {
20678            final PackageSetting ps = mSettings.mPackages.get(packageName);
20679            if (!filterAppAccessLPr(ps, callingUid, userId)
20680                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20681                            allowedByPermission, callingUid, userId)) {
20682                scheduleWritePackageRestrictionsLocked(userId);
20683            }
20684        }
20685    }
20686
20687    @Override
20688    public String getInstallerPackageName(String packageName) {
20689        final int callingUid = Binder.getCallingUid();
20690        if (getInstantAppPackageName(callingUid) != null) {
20691            return null;
20692        }
20693        // reader
20694        synchronized (mPackages) {
20695            final PackageSetting ps = mSettings.mPackages.get(packageName);
20696            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20697                return null;
20698            }
20699            return mSettings.getInstallerPackageNameLPr(packageName);
20700        }
20701    }
20702
20703    public boolean isOrphaned(String packageName) {
20704        // reader
20705        synchronized (mPackages) {
20706            return mSettings.isOrphaned(packageName);
20707        }
20708    }
20709
20710    @Override
20711    public int getApplicationEnabledSetting(String packageName, int userId) {
20712        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20713        int callingUid = Binder.getCallingUid();
20714        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20715                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20716        // reader
20717        synchronized (mPackages) {
20718            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
20719                return COMPONENT_ENABLED_STATE_DISABLED;
20720            }
20721            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20722        }
20723    }
20724
20725    @Override
20726    public int getComponentEnabledSetting(ComponentName component, int userId) {
20727        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20728        int callingUid = Binder.getCallingUid();
20729        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20730                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
20731        synchronized (mPackages) {
20732            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
20733                    component, TYPE_UNKNOWN, userId)) {
20734                return COMPONENT_ENABLED_STATE_DISABLED;
20735            }
20736            return mSettings.getComponentEnabledSettingLPr(component, userId);
20737        }
20738    }
20739
20740    @Override
20741    public void enterSafeMode() {
20742        enforceSystemOrRoot("Only the system can request entering safe mode");
20743
20744        if (!mSystemReady) {
20745            mSafeMode = true;
20746        }
20747    }
20748
20749    @Override
20750    public void systemReady() {
20751        enforceSystemOrRoot("Only the system can claim the system is ready");
20752
20753        mSystemReady = true;
20754        final ContentResolver resolver = mContext.getContentResolver();
20755        ContentObserver co = new ContentObserver(mHandler) {
20756            @Override
20757            public void onChange(boolean selfChange) {
20758                mEphemeralAppsDisabled =
20759                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20760                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20761            }
20762        };
20763        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20764                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20765                false, co, UserHandle.USER_SYSTEM);
20766        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20767                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20768        co.onChange(true);
20769
20770        // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to
20771        // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once
20772        // it is done.
20773        ContentObserver privAppOobObserver = new ContentObserver(mHandler) {
20774            @Override
20775            public void onChange(boolean selfChange) {
20776                int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0);
20777                SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB,
20778                        oobEnabled == 1 ? "true" : "false");
20779            }
20780        };
20781        mContext.getContentResolver().registerContentObserver(
20782                Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver,
20783                UserHandle.USER_SYSTEM);
20784        // At boot, restore the value from the setting, which persists across reboot.
20785        privAppOobObserver.onChange(true);
20786
20787        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20788        // disabled after already being started.
20789        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20790                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20791
20792        // Read the compatibilty setting when the system is ready.
20793        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20794                mContext.getContentResolver(),
20795                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20796        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20797        if (DEBUG_SETTINGS) {
20798            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20799        }
20800
20801        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20802
20803        synchronized (mPackages) {
20804            // Verify that all of the preferred activity components actually
20805            // exist.  It is possible for applications to be updated and at
20806            // that point remove a previously declared activity component that
20807            // had been set as a preferred activity.  We try to clean this up
20808            // the next time we encounter that preferred activity, but it is
20809            // possible for the user flow to never be able to return to that
20810            // situation so here we do a sanity check to make sure we haven't
20811            // left any junk around.
20812            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20813            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20814                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20815                removed.clear();
20816                for (PreferredActivity pa : pir.filterSet()) {
20817                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20818                        removed.add(pa);
20819                    }
20820                }
20821                if (removed.size() > 0) {
20822                    for (int r=0; r<removed.size(); r++) {
20823                        PreferredActivity pa = removed.get(r);
20824                        Slog.w(TAG, "Removing dangling preferred activity: "
20825                                + pa.mPref.mComponent);
20826                        pir.removeFilter(pa);
20827                    }
20828                    mSettings.writePackageRestrictionsLPr(
20829                            mSettings.mPreferredActivities.keyAt(i));
20830                }
20831            }
20832
20833            for (int userId : UserManagerService.getInstance().getUserIds()) {
20834                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20835                    grantPermissionsUserIds = ArrayUtils.appendInt(
20836                            grantPermissionsUserIds, userId);
20837                }
20838            }
20839        }
20840        sUserManager.systemReady();
20841        // If we upgraded grant all default permissions before kicking off.
20842        for (int userId : grantPermissionsUserIds) {
20843            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20844        }
20845
20846        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20847            // If we did not grant default permissions, we preload from this the
20848            // default permission exceptions lazily to ensure we don't hit the
20849            // disk on a new user creation.
20850            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20851        }
20852
20853        // Now that we've scanned all packages, and granted any default
20854        // permissions, ensure permissions are updated. Beware of dragons if you
20855        // try optimizing this.
20856        synchronized (mPackages) {
20857            mPermissionManager.updateAllPermissions(
20858                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
20859                    mPermissionCallback);
20860        }
20861
20862        // Kick off any messages waiting for system ready
20863        if (mPostSystemReadyMessages != null) {
20864            for (Message msg : mPostSystemReadyMessages) {
20865                msg.sendToTarget();
20866            }
20867            mPostSystemReadyMessages = null;
20868        }
20869
20870        // Watch for external volumes that come and go over time
20871        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20872        storage.registerListener(mStorageListener);
20873
20874        mInstallerService.systemReady();
20875        mPackageDexOptimizer.systemReady();
20876
20877        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20878                StorageManagerInternal.class);
20879        StorageManagerInternal.addExternalStoragePolicy(
20880                new StorageManagerInternal.ExternalStorageMountPolicy() {
20881            @Override
20882            public int getMountMode(int uid, String packageName) {
20883                if (Process.isIsolated(uid)) {
20884                    return Zygote.MOUNT_EXTERNAL_NONE;
20885                }
20886                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
20887                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20888                }
20889                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20890                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20891                }
20892                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20893                    return Zygote.MOUNT_EXTERNAL_READ;
20894                }
20895                return Zygote.MOUNT_EXTERNAL_WRITE;
20896            }
20897
20898            @Override
20899            public boolean hasExternalStorage(int uid, String packageName) {
20900                return true;
20901            }
20902        });
20903
20904        // Now that we're mostly running, clean up stale users and apps
20905        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20906        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20907
20908        mPermissionManager.systemReady();
20909    }
20910
20911    public void waitForAppDataPrepared() {
20912        if (mPrepareAppDataFuture == null) {
20913            return;
20914        }
20915        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20916        mPrepareAppDataFuture = null;
20917    }
20918
20919    @Override
20920    public boolean isSafeMode() {
20921        // allow instant applications
20922        return mSafeMode;
20923    }
20924
20925    @Override
20926    public boolean hasSystemUidErrors() {
20927        // allow instant applications
20928        return mHasSystemUidErrors;
20929    }
20930
20931    static String arrayToString(int[] array) {
20932        StringBuffer buf = new StringBuffer(128);
20933        buf.append('[');
20934        if (array != null) {
20935            for (int i=0; i<array.length; i++) {
20936                if (i > 0) buf.append(", ");
20937                buf.append(array[i]);
20938            }
20939        }
20940        buf.append(']');
20941        return buf.toString();
20942    }
20943
20944    @Override
20945    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20946            FileDescriptor err, String[] args, ShellCallback callback,
20947            ResultReceiver resultReceiver) {
20948        (new PackageManagerShellCommand(this)).exec(
20949                this, in, out, err, args, callback, resultReceiver);
20950    }
20951
20952    @Override
20953    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20954        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
20955
20956        DumpState dumpState = new DumpState();
20957        boolean fullPreferred = false;
20958        boolean checkin = false;
20959
20960        String packageName = null;
20961        ArraySet<String> permissionNames = null;
20962
20963        int opti = 0;
20964        while (opti < args.length) {
20965            String opt = args[opti];
20966            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20967                break;
20968            }
20969            opti++;
20970
20971            if ("-a".equals(opt)) {
20972                // Right now we only know how to print all.
20973            } else if ("-h".equals(opt)) {
20974                pw.println("Package manager dump options:");
20975                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20976                pw.println("    --checkin: dump for a checkin");
20977                pw.println("    -f: print details of intent filters");
20978                pw.println("    -h: print this help");
20979                pw.println("  cmd may be one of:");
20980                pw.println("    l[ibraries]: list known shared libraries");
20981                pw.println("    f[eatures]: list device features");
20982                pw.println("    k[eysets]: print known keysets");
20983                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20984                pw.println("    perm[issions]: dump permissions");
20985                pw.println("    permission [name ...]: dump declaration and use of given permission");
20986                pw.println("    pref[erred]: print preferred package settings");
20987                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20988                pw.println("    prov[iders]: dump content providers");
20989                pw.println("    p[ackages]: dump installed packages");
20990                pw.println("    s[hared-users]: dump shared user IDs");
20991                pw.println("    m[essages]: print collected runtime messages");
20992                pw.println("    v[erifiers]: print package verifier info");
20993                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20994                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20995                pw.println("    version: print database version info");
20996                pw.println("    write: write current settings now");
20997                pw.println("    installs: details about install sessions");
20998                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20999                pw.println("    dexopt: dump dexopt state");
21000                pw.println("    compiler-stats: dump compiler statistics");
21001                pw.println("    enabled-overlays: dump list of enabled overlay packages");
21002                pw.println("    service-permissions: dump permissions required by services");
21003                pw.println("    <package.name>: info about given package");
21004                return;
21005            } else if ("--checkin".equals(opt)) {
21006                checkin = true;
21007            } else if ("-f".equals(opt)) {
21008                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21009            } else if ("--proto".equals(opt)) {
21010                dumpProto(fd);
21011                return;
21012            } else {
21013                pw.println("Unknown argument: " + opt + "; use -h for help");
21014            }
21015        }
21016
21017        // Is the caller requesting to dump a particular piece of data?
21018        if (opti < args.length) {
21019            String cmd = args[opti];
21020            opti++;
21021            // Is this a package name?
21022            if ("android".equals(cmd) || cmd.contains(".")) {
21023                packageName = cmd;
21024                // When dumping a single package, we always dump all of its
21025                // filter information since the amount of data will be reasonable.
21026                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21027            } else if ("check-permission".equals(cmd)) {
21028                if (opti >= args.length) {
21029                    pw.println("Error: check-permission missing permission argument");
21030                    return;
21031                }
21032                String perm = args[opti];
21033                opti++;
21034                if (opti >= args.length) {
21035                    pw.println("Error: check-permission missing package argument");
21036                    return;
21037                }
21038
21039                String pkg = args[opti];
21040                opti++;
21041                int user = UserHandle.getUserId(Binder.getCallingUid());
21042                if (opti < args.length) {
21043                    try {
21044                        user = Integer.parseInt(args[opti]);
21045                    } catch (NumberFormatException e) {
21046                        pw.println("Error: check-permission user argument is not a number: "
21047                                + args[opti]);
21048                        return;
21049                    }
21050                }
21051
21052                // Normalize package name to handle renamed packages and static libs
21053                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21054
21055                pw.println(checkPermission(perm, pkg, user));
21056                return;
21057            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21058                dumpState.setDump(DumpState.DUMP_LIBS);
21059            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21060                dumpState.setDump(DumpState.DUMP_FEATURES);
21061            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21062                if (opti >= args.length) {
21063                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21064                            | DumpState.DUMP_SERVICE_RESOLVERS
21065                            | DumpState.DUMP_RECEIVER_RESOLVERS
21066                            | DumpState.DUMP_CONTENT_RESOLVERS);
21067                } else {
21068                    while (opti < args.length) {
21069                        String name = args[opti];
21070                        if ("a".equals(name) || "activity".equals(name)) {
21071                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21072                        } else if ("s".equals(name) || "service".equals(name)) {
21073                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21074                        } else if ("r".equals(name) || "receiver".equals(name)) {
21075                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21076                        } else if ("c".equals(name) || "content".equals(name)) {
21077                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21078                        } else {
21079                            pw.println("Error: unknown resolver table type: " + name);
21080                            return;
21081                        }
21082                        opti++;
21083                    }
21084                }
21085            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21086                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21087            } else if ("permission".equals(cmd)) {
21088                if (opti >= args.length) {
21089                    pw.println("Error: permission requires permission name");
21090                    return;
21091                }
21092                permissionNames = new ArraySet<>();
21093                while (opti < args.length) {
21094                    permissionNames.add(args[opti]);
21095                    opti++;
21096                }
21097                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21098                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21099            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21100                dumpState.setDump(DumpState.DUMP_PREFERRED);
21101            } else if ("preferred-xml".equals(cmd)) {
21102                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21103                if (opti < args.length && "--full".equals(args[opti])) {
21104                    fullPreferred = true;
21105                    opti++;
21106                }
21107            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21108                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21109            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21110                dumpState.setDump(DumpState.DUMP_PACKAGES);
21111            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21112                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21113            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21114                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21115            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21116                dumpState.setDump(DumpState.DUMP_MESSAGES);
21117            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21118                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21119            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21120                    || "intent-filter-verifiers".equals(cmd)) {
21121                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21122            } else if ("version".equals(cmd)) {
21123                dumpState.setDump(DumpState.DUMP_VERSION);
21124            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21125                dumpState.setDump(DumpState.DUMP_KEYSETS);
21126            } else if ("installs".equals(cmd)) {
21127                dumpState.setDump(DumpState.DUMP_INSTALLS);
21128            } else if ("frozen".equals(cmd)) {
21129                dumpState.setDump(DumpState.DUMP_FROZEN);
21130            } else if ("volumes".equals(cmd)) {
21131                dumpState.setDump(DumpState.DUMP_VOLUMES);
21132            } else if ("dexopt".equals(cmd)) {
21133                dumpState.setDump(DumpState.DUMP_DEXOPT);
21134            } else if ("compiler-stats".equals(cmd)) {
21135                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21136            } else if ("changes".equals(cmd)) {
21137                dumpState.setDump(DumpState.DUMP_CHANGES);
21138            } else if ("service-permissions".equals(cmd)) {
21139                dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS);
21140            } else if ("write".equals(cmd)) {
21141                synchronized (mPackages) {
21142                    mSettings.writeLPr();
21143                    pw.println("Settings written.");
21144                    return;
21145                }
21146            }
21147        }
21148
21149        if (checkin) {
21150            pw.println("vers,1");
21151        }
21152
21153        // reader
21154        synchronized (mPackages) {
21155            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21156                if (!checkin) {
21157                    if (dumpState.onTitlePrinted())
21158                        pw.println();
21159                    pw.println("Database versions:");
21160                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21161                }
21162            }
21163
21164            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21165                if (!checkin) {
21166                    if (dumpState.onTitlePrinted())
21167                        pw.println();
21168                    pw.println("Verifiers:");
21169                    pw.print("  Required: ");
21170                    pw.print(mRequiredVerifierPackage);
21171                    pw.print(" (uid=");
21172                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21173                            UserHandle.USER_SYSTEM));
21174                    pw.println(")");
21175                } else if (mRequiredVerifierPackage != null) {
21176                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21177                    pw.print(",");
21178                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21179                            UserHandle.USER_SYSTEM));
21180                }
21181            }
21182
21183            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21184                    packageName == null) {
21185                if (mIntentFilterVerifierComponent != null) {
21186                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21187                    if (!checkin) {
21188                        if (dumpState.onTitlePrinted())
21189                            pw.println();
21190                        pw.println("Intent Filter Verifier:");
21191                        pw.print("  Using: ");
21192                        pw.print(verifierPackageName);
21193                        pw.print(" (uid=");
21194                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21195                                UserHandle.USER_SYSTEM));
21196                        pw.println(")");
21197                    } else if (verifierPackageName != null) {
21198                        pw.print("ifv,"); pw.print(verifierPackageName);
21199                        pw.print(",");
21200                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21201                                UserHandle.USER_SYSTEM));
21202                    }
21203                } else {
21204                    pw.println();
21205                    pw.println("No Intent Filter Verifier available!");
21206                }
21207            }
21208
21209            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21210                boolean printedHeader = false;
21211                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21212                while (it.hasNext()) {
21213                    String libName = it.next();
21214                    LongSparseArray<SharedLibraryEntry> versionedLib
21215                            = mSharedLibraries.get(libName);
21216                    if (versionedLib == null) {
21217                        continue;
21218                    }
21219                    final int versionCount = versionedLib.size();
21220                    for (int i = 0; i < versionCount; i++) {
21221                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21222                        if (!checkin) {
21223                            if (!printedHeader) {
21224                                if (dumpState.onTitlePrinted())
21225                                    pw.println();
21226                                pw.println("Libraries:");
21227                                printedHeader = true;
21228                            }
21229                            pw.print("  ");
21230                        } else {
21231                            pw.print("lib,");
21232                        }
21233                        pw.print(libEntry.info.getName());
21234                        if (libEntry.info.isStatic()) {
21235                            pw.print(" version=" + libEntry.info.getLongVersion());
21236                        }
21237                        if (!checkin) {
21238                            pw.print(" -> ");
21239                        }
21240                        if (libEntry.path != null) {
21241                            pw.print(" (jar) ");
21242                            pw.print(libEntry.path);
21243                        } else {
21244                            pw.print(" (apk) ");
21245                            pw.print(libEntry.apk);
21246                        }
21247                        pw.println();
21248                    }
21249                }
21250            }
21251
21252            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21253                if (dumpState.onTitlePrinted())
21254                    pw.println();
21255                if (!checkin) {
21256                    pw.println("Features:");
21257                }
21258
21259                synchronized (mAvailableFeatures) {
21260                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21261                        if (checkin) {
21262                            pw.print("feat,");
21263                            pw.print(feat.name);
21264                            pw.print(",");
21265                            pw.println(feat.version);
21266                        } else {
21267                            pw.print("  ");
21268                            pw.print(feat.name);
21269                            if (feat.version > 0) {
21270                                pw.print(" version=");
21271                                pw.print(feat.version);
21272                            }
21273                            pw.println();
21274                        }
21275                    }
21276                }
21277            }
21278
21279            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21280                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21281                        : "Activity Resolver Table:", "  ", packageName,
21282                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21283                    dumpState.setTitlePrinted(true);
21284                }
21285            }
21286            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21287                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21288                        : "Receiver Resolver Table:", "  ", packageName,
21289                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21290                    dumpState.setTitlePrinted(true);
21291                }
21292            }
21293            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21294                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21295                        : "Service Resolver Table:", "  ", packageName,
21296                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21297                    dumpState.setTitlePrinted(true);
21298                }
21299            }
21300            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21301                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21302                        : "Provider Resolver Table:", "  ", packageName,
21303                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21304                    dumpState.setTitlePrinted(true);
21305                }
21306            }
21307
21308            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21309                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21310                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21311                    int user = mSettings.mPreferredActivities.keyAt(i);
21312                    if (pir.dump(pw,
21313                            dumpState.getTitlePrinted()
21314                                ? "\nPreferred Activities User " + user + ":"
21315                                : "Preferred Activities User " + user + ":", "  ",
21316                            packageName, true, false)) {
21317                        dumpState.setTitlePrinted(true);
21318                    }
21319                }
21320            }
21321
21322            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21323                pw.flush();
21324                FileOutputStream fout = new FileOutputStream(fd);
21325                BufferedOutputStream str = new BufferedOutputStream(fout);
21326                XmlSerializer serializer = new FastXmlSerializer();
21327                try {
21328                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21329                    serializer.startDocument(null, true);
21330                    serializer.setFeature(
21331                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21332                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21333                    serializer.endDocument();
21334                    serializer.flush();
21335                } catch (IllegalArgumentException e) {
21336                    pw.println("Failed writing: " + e);
21337                } catch (IllegalStateException e) {
21338                    pw.println("Failed writing: " + e);
21339                } catch (IOException e) {
21340                    pw.println("Failed writing: " + e);
21341                }
21342            }
21343
21344            if (!checkin
21345                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21346                    && packageName == null) {
21347                pw.println();
21348                int count = mSettings.mPackages.size();
21349                if (count == 0) {
21350                    pw.println("No applications!");
21351                    pw.println();
21352                } else {
21353                    final String prefix = "  ";
21354                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21355                    if (allPackageSettings.size() == 0) {
21356                        pw.println("No domain preferred apps!");
21357                        pw.println();
21358                    } else {
21359                        pw.println("App verification status:");
21360                        pw.println();
21361                        count = 0;
21362                        for (PackageSetting ps : allPackageSettings) {
21363                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21364                            if (ivi == null || ivi.getPackageName() == null) continue;
21365                            pw.println(prefix + "Package: " + ivi.getPackageName());
21366                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21367                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21368                            pw.println();
21369                            count++;
21370                        }
21371                        if (count == 0) {
21372                            pw.println(prefix + "No app verification established.");
21373                            pw.println();
21374                        }
21375                        for (int userId : sUserManager.getUserIds()) {
21376                            pw.println("App linkages for user " + userId + ":");
21377                            pw.println();
21378                            count = 0;
21379                            for (PackageSetting ps : allPackageSettings) {
21380                                final long status = ps.getDomainVerificationStatusForUser(userId);
21381                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21382                                        && !DEBUG_DOMAIN_VERIFICATION) {
21383                                    continue;
21384                                }
21385                                pw.println(prefix + "Package: " + ps.name);
21386                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21387                                String statusStr = IntentFilterVerificationInfo.
21388                                        getStatusStringFromValue(status);
21389                                pw.println(prefix + "Status:  " + statusStr);
21390                                pw.println();
21391                                count++;
21392                            }
21393                            if (count == 0) {
21394                                pw.println(prefix + "No configured app linkages.");
21395                                pw.println();
21396                            }
21397                        }
21398                    }
21399                }
21400            }
21401
21402            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21403                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21404            }
21405
21406            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21407                boolean printedSomething = false;
21408                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21409                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21410                        continue;
21411                    }
21412                    if (!printedSomething) {
21413                        if (dumpState.onTitlePrinted())
21414                            pw.println();
21415                        pw.println("Registered ContentProviders:");
21416                        printedSomething = true;
21417                    }
21418                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21419                    pw.print("    "); pw.println(p.toString());
21420                }
21421                printedSomething = false;
21422                for (Map.Entry<String, PackageParser.Provider> entry :
21423                        mProvidersByAuthority.entrySet()) {
21424                    PackageParser.Provider p = entry.getValue();
21425                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21426                        continue;
21427                    }
21428                    if (!printedSomething) {
21429                        if (dumpState.onTitlePrinted())
21430                            pw.println();
21431                        pw.println("ContentProvider Authorities:");
21432                        printedSomething = true;
21433                    }
21434                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21435                    pw.print("    "); pw.println(p.toString());
21436                    if (p.info != null && p.info.applicationInfo != null) {
21437                        final String appInfo = p.info.applicationInfo.toString();
21438                        pw.print("      applicationInfo="); pw.println(appInfo);
21439                    }
21440                }
21441            }
21442
21443            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21444                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21445            }
21446
21447            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21448                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21449            }
21450
21451            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21452                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21453            }
21454
21455            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21456                if (dumpState.onTitlePrinted()) pw.println();
21457                pw.println("Package Changes:");
21458                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21459                final int K = mChangedPackages.size();
21460                for (int i = 0; i < K; i++) {
21461                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21462                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21463                    final int N = changes.size();
21464                    if (N == 0) {
21465                        pw.print("    "); pw.println("No packages changed");
21466                    } else {
21467                        for (int j = 0; j < N; j++) {
21468                            final String pkgName = changes.valueAt(j);
21469                            final int sequenceNumber = changes.keyAt(j);
21470                            pw.print("    ");
21471                            pw.print("seq=");
21472                            pw.print(sequenceNumber);
21473                            pw.print(", package=");
21474                            pw.println(pkgName);
21475                        }
21476                    }
21477                }
21478            }
21479
21480            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21481                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21482            }
21483
21484            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21485                // XXX should handle packageName != null by dumping only install data that
21486                // the given package is involved with.
21487                if (dumpState.onTitlePrinted()) pw.println();
21488
21489                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21490                ipw.println();
21491                ipw.println("Frozen packages:");
21492                ipw.increaseIndent();
21493                if (mFrozenPackages.size() == 0) {
21494                    ipw.println("(none)");
21495                } else {
21496                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21497                        ipw.println(mFrozenPackages.valueAt(i));
21498                    }
21499                }
21500                ipw.decreaseIndent();
21501            }
21502
21503            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
21504                if (dumpState.onTitlePrinted()) pw.println();
21505
21506                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21507                ipw.println();
21508                ipw.println("Loaded volumes:");
21509                ipw.increaseIndent();
21510                if (mLoadedVolumes.size() == 0) {
21511                    ipw.println("(none)");
21512                } else {
21513                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
21514                        ipw.println(mLoadedVolumes.valueAt(i));
21515                    }
21516                }
21517                ipw.decreaseIndent();
21518            }
21519
21520            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS)
21521                    && packageName == null) {
21522                if (dumpState.onTitlePrinted()) pw.println();
21523                pw.println("Service permissions:");
21524
21525                final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator();
21526                while (filterIterator.hasNext()) {
21527                    final ServiceIntentInfo info = filterIterator.next();
21528                    final ServiceInfo serviceInfo = info.service.info;
21529                    final String permission = serviceInfo.permission;
21530                    if (permission != null) {
21531                        pw.print("    ");
21532                        pw.print(serviceInfo.getComponentName().flattenToShortString());
21533                        pw.print(": ");
21534                        pw.println(permission);
21535                    }
21536                }
21537            }
21538
21539            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21540                if (dumpState.onTitlePrinted()) pw.println();
21541                dumpDexoptStateLPr(pw, packageName);
21542            }
21543
21544            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21545                if (dumpState.onTitlePrinted()) pw.println();
21546                dumpCompilerStatsLPr(pw, packageName);
21547            }
21548
21549            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21550                if (dumpState.onTitlePrinted()) pw.println();
21551                mSettings.dumpReadMessagesLPr(pw, dumpState);
21552
21553                pw.println();
21554                pw.println("Package warning messages:");
21555                dumpCriticalInfo(pw, null);
21556            }
21557
21558            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21559                dumpCriticalInfo(pw, "msg,");
21560            }
21561        }
21562
21563        // PackageInstaller should be called outside of mPackages lock
21564        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21565            // XXX should handle packageName != null by dumping only install data that
21566            // the given package is involved with.
21567            if (dumpState.onTitlePrinted()) pw.println();
21568            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21569        }
21570    }
21571
21572    private void dumpProto(FileDescriptor fd) {
21573        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21574
21575        synchronized (mPackages) {
21576            final long requiredVerifierPackageToken =
21577                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21578            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21579            proto.write(
21580                    PackageServiceDumpProto.PackageShortProto.UID,
21581                    getPackageUid(
21582                            mRequiredVerifierPackage,
21583                            MATCH_DEBUG_TRIAGED_MISSING,
21584                            UserHandle.USER_SYSTEM));
21585            proto.end(requiredVerifierPackageToken);
21586
21587            if (mIntentFilterVerifierComponent != null) {
21588                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21589                final long verifierPackageToken =
21590                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21591                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21592                proto.write(
21593                        PackageServiceDumpProto.PackageShortProto.UID,
21594                        getPackageUid(
21595                                verifierPackageName,
21596                                MATCH_DEBUG_TRIAGED_MISSING,
21597                                UserHandle.USER_SYSTEM));
21598                proto.end(verifierPackageToken);
21599            }
21600
21601            dumpSharedLibrariesProto(proto);
21602            dumpFeaturesProto(proto);
21603            mSettings.dumpPackagesProto(proto);
21604            mSettings.dumpSharedUsersProto(proto);
21605            dumpCriticalInfo(proto);
21606        }
21607        proto.flush();
21608    }
21609
21610    private void dumpFeaturesProto(ProtoOutputStream proto) {
21611        synchronized (mAvailableFeatures) {
21612            final int count = mAvailableFeatures.size();
21613            for (int i = 0; i < count; i++) {
21614                mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
21615            }
21616        }
21617    }
21618
21619    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21620        final int count = mSharedLibraries.size();
21621        for (int i = 0; i < count; i++) {
21622            final String libName = mSharedLibraries.keyAt(i);
21623            LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21624            if (versionedLib == null) {
21625                continue;
21626            }
21627            final int versionCount = versionedLib.size();
21628            for (int j = 0; j < versionCount; j++) {
21629                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21630                final long sharedLibraryToken =
21631                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21632                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21633                final boolean isJar = (libEntry.path != null);
21634                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21635                if (isJar) {
21636                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21637                } else {
21638                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21639                }
21640                proto.end(sharedLibraryToken);
21641            }
21642        }
21643    }
21644
21645    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21646        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21647        ipw.println();
21648        ipw.println("Dexopt state:");
21649        ipw.increaseIndent();
21650        Collection<PackageParser.Package> packages = null;
21651        if (packageName != null) {
21652            PackageParser.Package targetPackage = mPackages.get(packageName);
21653            if (targetPackage != null) {
21654                packages = Collections.singletonList(targetPackage);
21655            } else {
21656                ipw.println("Unable to find package: " + packageName);
21657                return;
21658            }
21659        } else {
21660            packages = mPackages.values();
21661        }
21662
21663        for (PackageParser.Package pkg : packages) {
21664            ipw.println("[" + pkg.packageName + "]");
21665            ipw.increaseIndent();
21666            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
21667                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
21668            ipw.decreaseIndent();
21669        }
21670    }
21671
21672    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21673        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21674        ipw.println();
21675        ipw.println("Compiler stats:");
21676        ipw.increaseIndent();
21677        Collection<PackageParser.Package> packages = null;
21678        if (packageName != null) {
21679            PackageParser.Package targetPackage = mPackages.get(packageName);
21680            if (targetPackage != null) {
21681                packages = Collections.singletonList(targetPackage);
21682            } else {
21683                ipw.println("Unable to find package: " + packageName);
21684                return;
21685            }
21686        } else {
21687            packages = mPackages.values();
21688        }
21689
21690        for (PackageParser.Package pkg : packages) {
21691            ipw.println("[" + pkg.packageName + "]");
21692            ipw.increaseIndent();
21693
21694            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21695            if (stats == null) {
21696                ipw.println("(No recorded stats)");
21697            } else {
21698                stats.dump(ipw);
21699            }
21700            ipw.decreaseIndent();
21701        }
21702    }
21703
21704    private String dumpDomainString(String packageName) {
21705        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21706                .getList();
21707        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21708
21709        ArraySet<String> result = new ArraySet<>();
21710        if (iviList.size() > 0) {
21711            for (IntentFilterVerificationInfo ivi : iviList) {
21712                for (String host : ivi.getDomains()) {
21713                    result.add(host);
21714                }
21715            }
21716        }
21717        if (filters != null && filters.size() > 0) {
21718            for (IntentFilter filter : filters) {
21719                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21720                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21721                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21722                    result.addAll(filter.getHostsList());
21723                }
21724            }
21725        }
21726
21727        StringBuilder sb = new StringBuilder(result.size() * 16);
21728        for (String domain : result) {
21729            if (sb.length() > 0) sb.append(" ");
21730            sb.append(domain);
21731        }
21732        return sb.toString();
21733    }
21734
21735    // ------- apps on sdcard specific code -------
21736    static final boolean DEBUG_SD_INSTALL = false;
21737
21738    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21739
21740    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21741
21742    private boolean mMediaMounted = false;
21743
21744    static String getEncryptKey() {
21745        try {
21746            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21747                    SD_ENCRYPTION_KEYSTORE_NAME);
21748            if (sdEncKey == null) {
21749                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21750                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21751                if (sdEncKey == null) {
21752                    Slog.e(TAG, "Failed to create encryption keys");
21753                    return null;
21754                }
21755            }
21756            return sdEncKey;
21757        } catch (NoSuchAlgorithmException nsae) {
21758            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21759            return null;
21760        } catch (IOException ioe) {
21761            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21762            return null;
21763        }
21764    }
21765
21766    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21767            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21768        final int size = infos.size();
21769        final String[] packageNames = new String[size];
21770        final int[] packageUids = new int[size];
21771        for (int i = 0; i < size; i++) {
21772            final ApplicationInfo info = infos.get(i);
21773            packageNames[i] = info.packageName;
21774            packageUids[i] = info.uid;
21775        }
21776        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21777                finishedReceiver);
21778    }
21779
21780    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21781            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21782        sendResourcesChangedBroadcast(mediaStatus, replacing,
21783                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21784    }
21785
21786    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21787            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21788        int size = pkgList.length;
21789        if (size > 0) {
21790            // Send broadcasts here
21791            Bundle extras = new Bundle();
21792            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21793            if (uidArr != null) {
21794                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21795            }
21796            if (replacing) {
21797                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21798            }
21799            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21800                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21801            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null);
21802        }
21803    }
21804
21805    private void loadPrivatePackages(final VolumeInfo vol) {
21806        mHandler.post(new Runnable() {
21807            @Override
21808            public void run() {
21809                loadPrivatePackagesInner(vol);
21810            }
21811        });
21812    }
21813
21814    private void loadPrivatePackagesInner(VolumeInfo vol) {
21815        final String volumeUuid = vol.fsUuid;
21816        if (TextUtils.isEmpty(volumeUuid)) {
21817            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21818            return;
21819        }
21820
21821        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21822        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21823        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21824
21825        final VersionInfo ver;
21826        final List<PackageSetting> packages;
21827        synchronized (mPackages) {
21828            ver = mSettings.findOrCreateVersion(volumeUuid);
21829            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21830        }
21831
21832        for (PackageSetting ps : packages) {
21833            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21834            synchronized (mInstallLock) {
21835                final PackageParser.Package pkg;
21836                try {
21837                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21838                    loaded.add(pkg.applicationInfo);
21839
21840                } catch (PackageManagerException e) {
21841                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21842                }
21843
21844                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21845                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21846                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21847                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21848                }
21849            }
21850        }
21851
21852        // Reconcile app data for all started/unlocked users
21853        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21854        final UserManager um = mContext.getSystemService(UserManager.class);
21855        UserManagerInternal umInternal = getUserManagerInternal();
21856        for (UserInfo user : um.getUsers()) {
21857            final int flags;
21858            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21859                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21860            } else if (umInternal.isUserRunning(user.id)) {
21861                flags = StorageManager.FLAG_STORAGE_DE;
21862            } else {
21863                continue;
21864            }
21865
21866            try {
21867                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21868                synchronized (mInstallLock) {
21869                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21870                }
21871            } catch (IllegalStateException e) {
21872                // Device was probably ejected, and we'll process that event momentarily
21873                Slog.w(TAG, "Failed to prepare storage: " + e);
21874            }
21875        }
21876
21877        synchronized (mPackages) {
21878            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
21879            if (sdkUpdated) {
21880                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21881                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21882            }
21883            mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(),
21884                    mPermissionCallback);
21885
21886            // Yay, everything is now upgraded
21887            ver.forceCurrent();
21888
21889            mSettings.writeLPr();
21890        }
21891
21892        for (PackageFreezer freezer : freezers) {
21893            freezer.close();
21894        }
21895
21896        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21897        sendResourcesChangedBroadcast(true, false, loaded, null);
21898        mLoadedVolumes.add(vol.getId());
21899    }
21900
21901    private void unloadPrivatePackages(final VolumeInfo vol) {
21902        mHandler.post(new Runnable() {
21903            @Override
21904            public void run() {
21905                unloadPrivatePackagesInner(vol);
21906            }
21907        });
21908    }
21909
21910    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21911        final String volumeUuid = vol.fsUuid;
21912        if (TextUtils.isEmpty(volumeUuid)) {
21913            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21914            return;
21915        }
21916
21917        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21918        synchronized (mInstallLock) {
21919        synchronized (mPackages) {
21920            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21921            for (PackageSetting ps : packages) {
21922                if (ps.pkg == null) continue;
21923
21924                final ApplicationInfo info = ps.pkg.applicationInfo;
21925                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21926                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
21927
21928                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21929                        "unloadPrivatePackagesInner")) {
21930                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21931                            false, null)) {
21932                        unloaded.add(info);
21933                    } else {
21934                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21935                    }
21936                }
21937
21938                // Try very hard to release any references to this package
21939                // so we don't risk the system server being killed due to
21940                // open FDs
21941                AttributeCache.instance().removePackage(ps.name);
21942            }
21943
21944            mSettings.writeLPr();
21945        }
21946        }
21947
21948        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21949        sendResourcesChangedBroadcast(false, false, unloaded, null);
21950        mLoadedVolumes.remove(vol.getId());
21951
21952        // Try very hard to release any references to this path so we don't risk
21953        // the system server being killed due to open FDs
21954        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21955
21956        for (int i = 0; i < 3; i++) {
21957            System.gc();
21958            System.runFinalization();
21959        }
21960    }
21961
21962    private void assertPackageKnown(String volumeUuid, String packageName)
21963            throws PackageManagerException {
21964        synchronized (mPackages) {
21965            // Normalize package name to handle renamed packages
21966            packageName = normalizePackageNameLPr(packageName);
21967
21968            final PackageSetting ps = mSettings.mPackages.get(packageName);
21969            if (ps == null) {
21970                throw new PackageManagerException("Package " + packageName + " is unknown");
21971            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21972                throw new PackageManagerException(
21973                        "Package " + packageName + " found on unknown volume " + volumeUuid
21974                                + "; expected volume " + ps.volumeUuid);
21975            }
21976        }
21977    }
21978
21979    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21980            throws PackageManagerException {
21981        synchronized (mPackages) {
21982            // Normalize package name to handle renamed packages
21983            packageName = normalizePackageNameLPr(packageName);
21984
21985            final PackageSetting ps = mSettings.mPackages.get(packageName);
21986            if (ps == null) {
21987                throw new PackageManagerException("Package " + packageName + " is unknown");
21988            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21989                throw new PackageManagerException(
21990                        "Package " + packageName + " found on unknown volume " + volumeUuid
21991                                + "; expected volume " + ps.volumeUuid);
21992            } else if (!ps.getInstalled(userId)) {
21993                throw new PackageManagerException(
21994                        "Package " + packageName + " not installed for user " + userId);
21995            }
21996        }
21997    }
21998
21999    private List<String> collectAbsoluteCodePaths() {
22000        synchronized (mPackages) {
22001            List<String> codePaths = new ArrayList<>();
22002            final int packageCount = mSettings.mPackages.size();
22003            for (int i = 0; i < packageCount; i++) {
22004                final PackageSetting ps = mSettings.mPackages.valueAt(i);
22005                codePaths.add(ps.codePath.getAbsolutePath());
22006            }
22007            return codePaths;
22008        }
22009    }
22010
22011    /**
22012     * Examine all apps present on given mounted volume, and destroy apps that
22013     * aren't expected, either due to uninstallation or reinstallation on
22014     * another volume.
22015     */
22016    private void reconcileApps(String volumeUuid) {
22017        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
22018        List<File> filesToDelete = null;
22019
22020        final File[] files = FileUtils.listFilesOrEmpty(
22021                Environment.getDataAppDirectory(volumeUuid));
22022        for (File file : files) {
22023            final boolean isPackage = (isApkFile(file) || file.isDirectory())
22024                    && !PackageInstallerService.isStageName(file.getName());
22025            if (!isPackage) {
22026                // Ignore entries which are not packages
22027                continue;
22028            }
22029
22030            String absolutePath = file.getAbsolutePath();
22031
22032            boolean pathValid = false;
22033            final int absoluteCodePathCount = absoluteCodePaths.size();
22034            for (int i = 0; i < absoluteCodePathCount; i++) {
22035                String absoluteCodePath = absoluteCodePaths.get(i);
22036                if (absolutePath.startsWith(absoluteCodePath)) {
22037                    pathValid = true;
22038                    break;
22039                }
22040            }
22041
22042            if (!pathValid) {
22043                if (filesToDelete == null) {
22044                    filesToDelete = new ArrayList<>();
22045                }
22046                filesToDelete.add(file);
22047            }
22048        }
22049
22050        if (filesToDelete != null) {
22051            final int fileToDeleteCount = filesToDelete.size();
22052            for (int i = 0; i < fileToDeleteCount; i++) {
22053                File fileToDelete = filesToDelete.get(i);
22054                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22055                synchronized (mInstallLock) {
22056                    removeCodePathLI(fileToDelete);
22057                }
22058            }
22059        }
22060    }
22061
22062    /**
22063     * Reconcile all app data for the given user.
22064     * <p>
22065     * Verifies that directories exist and that ownership and labeling is
22066     * correct for all installed apps on all mounted volumes.
22067     */
22068    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22069        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22070        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22071            final String volumeUuid = vol.getFsUuid();
22072            synchronized (mInstallLock) {
22073                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22074            }
22075        }
22076    }
22077
22078    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22079            boolean migrateAppData) {
22080        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22081    }
22082
22083    /**
22084     * Reconcile all app data on given mounted volume.
22085     * <p>
22086     * Destroys app data that isn't expected, either due to uninstallation or
22087     * reinstallation on another volume.
22088     * <p>
22089     * Verifies that directories exist and that ownership and labeling is
22090     * correct for all installed apps.
22091     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22092     */
22093    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22094            boolean migrateAppData, boolean onlyCoreApps) {
22095        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22096                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22097        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22098
22099        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22100        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22101
22102        // First look for stale data that doesn't belong, and check if things
22103        // have changed since we did our last restorecon
22104        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22105            if (StorageManager.isFileEncryptedNativeOrEmulated()
22106                    && !StorageManager.isUserKeyUnlocked(userId)) {
22107                throw new RuntimeException(
22108                        "Yikes, someone asked us to reconcile CE storage while " + userId
22109                                + " was still locked; this would have caused massive data loss!");
22110            }
22111
22112            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22113            for (File file : files) {
22114                final String packageName = file.getName();
22115                try {
22116                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22117                } catch (PackageManagerException e) {
22118                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22119                    try {
22120                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22121                                StorageManager.FLAG_STORAGE_CE, 0);
22122                    } catch (InstallerException e2) {
22123                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22124                    }
22125                }
22126            }
22127        }
22128        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22129            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22130            for (File file : files) {
22131                final String packageName = file.getName();
22132                try {
22133                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22134                } catch (PackageManagerException e) {
22135                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22136                    try {
22137                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22138                                StorageManager.FLAG_STORAGE_DE, 0);
22139                    } catch (InstallerException e2) {
22140                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22141                    }
22142                }
22143            }
22144        }
22145
22146        // Ensure that data directories are ready to roll for all packages
22147        // installed for this volume and user
22148        final List<PackageSetting> packages;
22149        synchronized (mPackages) {
22150            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22151        }
22152        int preparedCount = 0;
22153        for (PackageSetting ps : packages) {
22154            final String packageName = ps.name;
22155            if (ps.pkg == null) {
22156                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22157                // TODO: might be due to legacy ASEC apps; we should circle back
22158                // and reconcile again once they're scanned
22159                continue;
22160            }
22161            // Skip non-core apps if requested
22162            if (onlyCoreApps && !ps.pkg.coreApp) {
22163                result.add(packageName);
22164                continue;
22165            }
22166
22167            if (ps.getInstalled(userId)) {
22168                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22169                preparedCount++;
22170            }
22171        }
22172
22173        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22174        return result;
22175    }
22176
22177    /**
22178     * Prepare app data for the given app just after it was installed or
22179     * upgraded. This method carefully only touches users that it's installed
22180     * for, and it forces a restorecon to handle any seinfo changes.
22181     * <p>
22182     * Verifies that directories exist and that ownership and labeling is
22183     * correct for all installed apps. If there is an ownership mismatch, it
22184     * will try recovering system apps by wiping data; third-party app data is
22185     * left intact.
22186     * <p>
22187     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22188     */
22189    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22190        final PackageSetting ps;
22191        synchronized (mPackages) {
22192            ps = mSettings.mPackages.get(pkg.packageName);
22193            mSettings.writeKernelMappingLPr(ps);
22194        }
22195
22196        final UserManager um = mContext.getSystemService(UserManager.class);
22197        UserManagerInternal umInternal = getUserManagerInternal();
22198        for (UserInfo user : um.getUsers()) {
22199            final int flags;
22200            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22201                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22202            } else if (umInternal.isUserRunning(user.id)) {
22203                flags = StorageManager.FLAG_STORAGE_DE;
22204            } else {
22205                continue;
22206            }
22207
22208            if (ps.getInstalled(user.id)) {
22209                // TODO: when user data is locked, mark that we're still dirty
22210                prepareAppDataLIF(pkg, user.id, flags);
22211            }
22212        }
22213    }
22214
22215    /**
22216     * Prepare app data for the given app.
22217     * <p>
22218     * Verifies that directories exist and that ownership and labeling is
22219     * correct for all installed apps. If there is an ownership mismatch, this
22220     * will try recovering system apps by wiping data; third-party app data is
22221     * left intact.
22222     */
22223    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22224        if (pkg == null) {
22225            Slog.wtf(TAG, "Package was null!", new Throwable());
22226            return;
22227        }
22228        prepareAppDataLeafLIF(pkg, userId, flags);
22229        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22230        for (int i = 0; i < childCount; i++) {
22231            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22232        }
22233    }
22234
22235    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22236            boolean maybeMigrateAppData) {
22237        prepareAppDataLIF(pkg, userId, flags);
22238
22239        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22240            // We may have just shuffled around app data directories, so
22241            // prepare them one more time
22242            prepareAppDataLIF(pkg, userId, flags);
22243        }
22244    }
22245
22246    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22247        if (DEBUG_APP_DATA) {
22248            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22249                    + Integer.toHexString(flags));
22250        }
22251
22252        final String volumeUuid = pkg.volumeUuid;
22253        final String packageName = pkg.packageName;
22254        final ApplicationInfo app = pkg.applicationInfo;
22255        final int appId = UserHandle.getAppId(app.uid);
22256
22257        Preconditions.checkNotNull(app.seInfo);
22258
22259        long ceDataInode = -1;
22260        try {
22261            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22262                    appId, app.seInfo, app.targetSdkVersion);
22263        } catch (InstallerException e) {
22264            if (app.isSystemApp()) {
22265                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22266                        + ", but trying to recover: " + e);
22267                destroyAppDataLeafLIF(pkg, userId, flags);
22268                try {
22269                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22270                            appId, app.seInfo, app.targetSdkVersion);
22271                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22272                } catch (InstallerException e2) {
22273                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22274                }
22275            } else {
22276                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22277            }
22278        }
22279        // Prepare the application profiles.
22280        mArtManagerService.prepareAppProfiles(pkg, userId);
22281
22282        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22283            // TODO: mark this structure as dirty so we persist it!
22284            synchronized (mPackages) {
22285                final PackageSetting ps = mSettings.mPackages.get(packageName);
22286                if (ps != null) {
22287                    ps.setCeDataInode(ceDataInode, userId);
22288                }
22289            }
22290        }
22291
22292        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22293    }
22294
22295    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22296        if (pkg == null) {
22297            Slog.wtf(TAG, "Package was null!", new Throwable());
22298            return;
22299        }
22300        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22301        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22302        for (int i = 0; i < childCount; i++) {
22303            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22304        }
22305    }
22306
22307    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22308        final String volumeUuid = pkg.volumeUuid;
22309        final String packageName = pkg.packageName;
22310        final ApplicationInfo app = pkg.applicationInfo;
22311
22312        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22313            // Create a native library symlink only if we have native libraries
22314            // and if the native libraries are 32 bit libraries. We do not provide
22315            // this symlink for 64 bit libraries.
22316            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22317                final String nativeLibPath = app.nativeLibraryDir;
22318                try {
22319                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22320                            nativeLibPath, userId);
22321                } catch (InstallerException e) {
22322                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22323                }
22324            }
22325        }
22326    }
22327
22328    /**
22329     * For system apps on non-FBE devices, this method migrates any existing
22330     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22331     * requested by the app.
22332     */
22333    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22334        if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated()
22335                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22336            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22337                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22338            try {
22339                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22340                        storageTarget);
22341            } catch (InstallerException e) {
22342                logCriticalInfo(Log.WARN,
22343                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22344            }
22345            return true;
22346        } else {
22347            return false;
22348        }
22349    }
22350
22351    public PackageFreezer freezePackage(String packageName, String killReason) {
22352        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22353    }
22354
22355    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22356        return new PackageFreezer(packageName, userId, killReason);
22357    }
22358
22359    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22360            String killReason) {
22361        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22362    }
22363
22364    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22365            String killReason) {
22366        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22367            return new PackageFreezer();
22368        } else {
22369            return freezePackage(packageName, userId, killReason);
22370        }
22371    }
22372
22373    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22374            String killReason) {
22375        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22376    }
22377
22378    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22379            String killReason) {
22380        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22381            return new PackageFreezer();
22382        } else {
22383            return freezePackage(packageName, userId, killReason);
22384        }
22385    }
22386
22387    /**
22388     * Class that freezes and kills the given package upon creation, and
22389     * unfreezes it upon closing. This is typically used when doing surgery on
22390     * app code/data to prevent the app from running while you're working.
22391     */
22392    private class PackageFreezer implements AutoCloseable {
22393        private final String mPackageName;
22394        private final PackageFreezer[] mChildren;
22395
22396        private final boolean mWeFroze;
22397
22398        private final AtomicBoolean mClosed = new AtomicBoolean();
22399        private final CloseGuard mCloseGuard = CloseGuard.get();
22400
22401        /**
22402         * Create and return a stub freezer that doesn't actually do anything,
22403         * typically used when someone requested
22404         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22405         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22406         */
22407        public PackageFreezer() {
22408            mPackageName = null;
22409            mChildren = null;
22410            mWeFroze = false;
22411            mCloseGuard.open("close");
22412        }
22413
22414        public PackageFreezer(String packageName, int userId, String killReason) {
22415            synchronized (mPackages) {
22416                mPackageName = packageName;
22417                mWeFroze = mFrozenPackages.add(mPackageName);
22418
22419                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22420                if (ps != null) {
22421                    killApplication(ps.name, ps.appId, userId, killReason);
22422                }
22423
22424                final PackageParser.Package p = mPackages.get(packageName);
22425                if (p != null && p.childPackages != null) {
22426                    final int N = p.childPackages.size();
22427                    mChildren = new PackageFreezer[N];
22428                    for (int i = 0; i < N; i++) {
22429                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22430                                userId, killReason);
22431                    }
22432                } else {
22433                    mChildren = null;
22434                }
22435            }
22436            mCloseGuard.open("close");
22437        }
22438
22439        @Override
22440        protected void finalize() throws Throwable {
22441            try {
22442                if (mCloseGuard != null) {
22443                    mCloseGuard.warnIfOpen();
22444                }
22445
22446                close();
22447            } finally {
22448                super.finalize();
22449            }
22450        }
22451
22452        @Override
22453        public void close() {
22454            mCloseGuard.close();
22455            if (mClosed.compareAndSet(false, true)) {
22456                synchronized (mPackages) {
22457                    if (mWeFroze) {
22458                        mFrozenPackages.remove(mPackageName);
22459                    }
22460
22461                    if (mChildren != null) {
22462                        for (PackageFreezer freezer : mChildren) {
22463                            freezer.close();
22464                        }
22465                    }
22466                }
22467            }
22468        }
22469    }
22470
22471    /**
22472     * Verify that given package is currently frozen.
22473     */
22474    private void checkPackageFrozen(String packageName) {
22475        synchronized (mPackages) {
22476            if (!mFrozenPackages.contains(packageName)) {
22477                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22478            }
22479        }
22480    }
22481
22482    @Override
22483    public int movePackage(final String packageName, final String volumeUuid) {
22484        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22485
22486        final int callingUid = Binder.getCallingUid();
22487        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
22488        final int moveId = mNextMoveId.getAndIncrement();
22489        mHandler.post(new Runnable() {
22490            @Override
22491            public void run() {
22492                try {
22493                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
22494                } catch (PackageManagerException e) {
22495                    Slog.w(TAG, "Failed to move " + packageName, e);
22496                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
22497                }
22498            }
22499        });
22500        return moveId;
22501    }
22502
22503    private void movePackageInternal(final String packageName, final String volumeUuid,
22504            final int moveId, final int callingUid, UserHandle user)
22505                    throws PackageManagerException {
22506        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22507        final PackageManager pm = mContext.getPackageManager();
22508
22509        final boolean currentAsec;
22510        final String currentVolumeUuid;
22511        final File codeFile;
22512        final String installerPackageName;
22513        final String packageAbiOverride;
22514        final int appId;
22515        final String seinfo;
22516        final String label;
22517        final int targetSdkVersion;
22518        final PackageFreezer freezer;
22519        final int[] installedUserIds;
22520
22521        // reader
22522        synchronized (mPackages) {
22523            final PackageParser.Package pkg = mPackages.get(packageName);
22524            final PackageSetting ps = mSettings.mPackages.get(packageName);
22525            if (pkg == null
22526                    || ps == null
22527                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
22528                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22529            }
22530            if (pkg.applicationInfo.isSystemApp()) {
22531                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22532                        "Cannot move system application");
22533            }
22534
22535            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22536            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22537                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22538            if (isInternalStorage && !allow3rdPartyOnInternal) {
22539                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22540                        "3rd party apps are not allowed on internal storage");
22541            }
22542
22543            if (pkg.applicationInfo.isExternalAsec()) {
22544                currentAsec = true;
22545                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22546            } else if (pkg.applicationInfo.isForwardLocked()) {
22547                currentAsec = true;
22548                currentVolumeUuid = "forward_locked";
22549            } else {
22550                currentAsec = false;
22551                currentVolumeUuid = ps.volumeUuid;
22552
22553                final File probe = new File(pkg.codePath);
22554                final File probeOat = new File(probe, "oat");
22555                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22556                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22557                            "Move only supported for modern cluster style installs");
22558                }
22559            }
22560
22561            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22562                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22563                        "Package already moved to " + volumeUuid);
22564            }
22565            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22566                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22567                        "Device admin cannot be moved");
22568            }
22569
22570            if (mFrozenPackages.contains(packageName)) {
22571                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22572                        "Failed to move already frozen package");
22573            }
22574
22575            codeFile = new File(pkg.codePath);
22576            installerPackageName = ps.installerPackageName;
22577            packageAbiOverride = ps.cpuAbiOverrideString;
22578            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22579            seinfo = pkg.applicationInfo.seInfo;
22580            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22581            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22582            freezer = freezePackage(packageName, "movePackageInternal");
22583            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22584        }
22585
22586        final Bundle extras = new Bundle();
22587        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22588        extras.putString(Intent.EXTRA_TITLE, label);
22589        mMoveCallbacks.notifyCreated(moveId, extras);
22590
22591        int installFlags;
22592        final boolean moveCompleteApp;
22593        final File measurePath;
22594
22595        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22596            installFlags = INSTALL_INTERNAL;
22597            moveCompleteApp = !currentAsec;
22598            measurePath = Environment.getDataAppDirectory(volumeUuid);
22599        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22600            installFlags = INSTALL_EXTERNAL;
22601            moveCompleteApp = false;
22602            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22603        } else {
22604            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22605            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22606                    || !volume.isMountedWritable()) {
22607                freezer.close();
22608                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22609                        "Move location not mounted private volume");
22610            }
22611
22612            Preconditions.checkState(!currentAsec);
22613
22614            installFlags = INSTALL_INTERNAL;
22615            moveCompleteApp = true;
22616            measurePath = Environment.getDataAppDirectory(volumeUuid);
22617        }
22618
22619        // If we're moving app data around, we need all the users unlocked
22620        if (moveCompleteApp) {
22621            for (int userId : installedUserIds) {
22622                if (StorageManager.isFileEncryptedNativeOrEmulated()
22623                        && !StorageManager.isUserKeyUnlocked(userId)) {
22624                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
22625                            "User " + userId + " must be unlocked");
22626                }
22627            }
22628        }
22629
22630        final PackageStats stats = new PackageStats(null, -1);
22631        synchronized (mInstaller) {
22632            for (int userId : installedUserIds) {
22633                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22634                    freezer.close();
22635                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22636                            "Failed to measure package size");
22637                }
22638            }
22639        }
22640
22641        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22642                + stats.dataSize);
22643
22644        final long startFreeBytes = measurePath.getUsableSpace();
22645        final long sizeBytes;
22646        if (moveCompleteApp) {
22647            sizeBytes = stats.codeSize + stats.dataSize;
22648        } else {
22649            sizeBytes = stats.codeSize;
22650        }
22651
22652        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22653            freezer.close();
22654            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22655                    "Not enough free space to move");
22656        }
22657
22658        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22659
22660        final CountDownLatch installedLatch = new CountDownLatch(1);
22661        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22662            @Override
22663            public void onUserActionRequired(Intent intent) throws RemoteException {
22664                throw new IllegalStateException();
22665            }
22666
22667            @Override
22668            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22669                    Bundle extras) throws RemoteException {
22670                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22671                        + PackageManager.installStatusToString(returnCode, msg));
22672
22673                installedLatch.countDown();
22674                freezer.close();
22675
22676                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22677                switch (status) {
22678                    case PackageInstaller.STATUS_SUCCESS:
22679                        mMoveCallbacks.notifyStatusChanged(moveId,
22680                                PackageManager.MOVE_SUCCEEDED);
22681                        break;
22682                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22683                        mMoveCallbacks.notifyStatusChanged(moveId,
22684                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22685                        break;
22686                    default:
22687                        mMoveCallbacks.notifyStatusChanged(moveId,
22688                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22689                        break;
22690                }
22691            }
22692        };
22693
22694        final MoveInfo move;
22695        if (moveCompleteApp) {
22696            // Kick off a thread to report progress estimates
22697            new Thread() {
22698                @Override
22699                public void run() {
22700                    while (true) {
22701                        try {
22702                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22703                                break;
22704                            }
22705                        } catch (InterruptedException ignored) {
22706                        }
22707
22708                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22709                        final int progress = 10 + (int) MathUtils.constrain(
22710                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22711                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22712                    }
22713                }
22714            }.start();
22715
22716            final String dataAppName = codeFile.getName();
22717            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22718                    dataAppName, appId, seinfo, targetSdkVersion);
22719        } else {
22720            move = null;
22721        }
22722
22723        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22724
22725        final Message msg = mHandler.obtainMessage(INIT_COPY);
22726        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22727        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22728                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22729                packageAbiOverride, null /*grantedPermissions*/,
22730                PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN);
22731        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22732        msg.obj = params;
22733
22734        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22735                System.identityHashCode(msg.obj));
22736        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22737                System.identityHashCode(msg.obj));
22738
22739        mHandler.sendMessage(msg);
22740    }
22741
22742    @Override
22743    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22744        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22745
22746        final int realMoveId = mNextMoveId.getAndIncrement();
22747        final Bundle extras = new Bundle();
22748        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22749        mMoveCallbacks.notifyCreated(realMoveId, extras);
22750
22751        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22752            @Override
22753            public void onCreated(int moveId, Bundle extras) {
22754                // Ignored
22755            }
22756
22757            @Override
22758            public void onStatusChanged(int moveId, int status, long estMillis) {
22759                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22760            }
22761        };
22762
22763        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22764        storage.setPrimaryStorageUuid(volumeUuid, callback);
22765        return realMoveId;
22766    }
22767
22768    @Override
22769    public int getMoveStatus(int moveId) {
22770        mContext.enforceCallingOrSelfPermission(
22771                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22772        return mMoveCallbacks.mLastStatus.get(moveId);
22773    }
22774
22775    @Override
22776    public void registerMoveCallback(IPackageMoveObserver callback) {
22777        mContext.enforceCallingOrSelfPermission(
22778                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22779        mMoveCallbacks.register(callback);
22780    }
22781
22782    @Override
22783    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22784        mContext.enforceCallingOrSelfPermission(
22785                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22786        mMoveCallbacks.unregister(callback);
22787    }
22788
22789    @Override
22790    public boolean setInstallLocation(int loc) {
22791        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22792                null);
22793        if (getInstallLocation() == loc) {
22794            return true;
22795        }
22796        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22797                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22798            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22799                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22800            return true;
22801        }
22802        return false;
22803   }
22804
22805    @Override
22806    public int getInstallLocation() {
22807        // allow instant app access
22808        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22809                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22810                PackageHelper.APP_INSTALL_AUTO);
22811    }
22812
22813    /** Called by UserManagerService */
22814    void cleanUpUser(UserManagerService userManager, int userHandle) {
22815        synchronized (mPackages) {
22816            mDirtyUsers.remove(userHandle);
22817            mUserNeedsBadging.delete(userHandle);
22818            mSettings.removeUserLPw(userHandle);
22819            mPendingBroadcasts.remove(userHandle);
22820            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22821            removeUnusedPackagesLPw(userManager, userHandle);
22822        }
22823    }
22824
22825    /**
22826     * We're removing userHandle and would like to remove any downloaded packages
22827     * that are no longer in use by any other user.
22828     * @param userHandle the user being removed
22829     */
22830    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22831        final boolean DEBUG_CLEAN_APKS = false;
22832        int [] users = userManager.getUserIds();
22833        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22834        while (psit.hasNext()) {
22835            PackageSetting ps = psit.next();
22836            if (ps.pkg == null) {
22837                continue;
22838            }
22839            final String packageName = ps.pkg.packageName;
22840            // Skip over if system app
22841            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22842                continue;
22843            }
22844            if (DEBUG_CLEAN_APKS) {
22845                Slog.i(TAG, "Checking package " + packageName);
22846            }
22847            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22848            if (keep) {
22849                if (DEBUG_CLEAN_APKS) {
22850                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22851                }
22852            } else {
22853                for (int i = 0; i < users.length; i++) {
22854                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22855                        keep = true;
22856                        if (DEBUG_CLEAN_APKS) {
22857                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22858                                    + users[i]);
22859                        }
22860                        break;
22861                    }
22862                }
22863            }
22864            if (!keep) {
22865                if (DEBUG_CLEAN_APKS) {
22866                    Slog.i(TAG, "  Removing package " + packageName);
22867                }
22868                mHandler.post(new Runnable() {
22869                    public void run() {
22870                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22871                                userHandle, 0);
22872                    } //end run
22873                });
22874            }
22875        }
22876    }
22877
22878    /** Called by UserManagerService */
22879    void createNewUser(int userId, String[] disallowedPackages) {
22880        synchronized (mInstallLock) {
22881            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22882        }
22883        synchronized (mPackages) {
22884            scheduleWritePackageRestrictionsLocked(userId);
22885            scheduleWritePackageListLocked(userId);
22886            applyFactoryDefaultBrowserLPw(userId);
22887            primeDomainVerificationsLPw(userId);
22888        }
22889    }
22890
22891    void onNewUserCreated(final int userId) {
22892        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22893        synchronized(mPackages) {
22894            // If permission review for legacy apps is required, we represent
22895            // dagerous permissions for such apps as always granted runtime
22896            // permissions to keep per user flag state whether review is needed.
22897            // Hence, if a new user is added we have to propagate dangerous
22898            // permission grants for these legacy apps.
22899            if (mSettings.mPermissions.mPermissionReviewRequired) {
22900// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG
22901                mPermissionManager.updateAllPermissions(
22902                        StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(),
22903                        mPermissionCallback);
22904            }
22905        }
22906    }
22907
22908    @Override
22909    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22910        mContext.enforceCallingOrSelfPermission(
22911                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22912                "Only package verification agents can read the verifier device identity");
22913
22914        synchronized (mPackages) {
22915            return mSettings.getVerifierDeviceIdentityLPw();
22916        }
22917    }
22918
22919    @Override
22920    public void setPermissionEnforced(String permission, boolean enforced) {
22921        // TODO: Now that we no longer change GID for storage, this should to away.
22922        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22923                "setPermissionEnforced");
22924        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22925            synchronized (mPackages) {
22926                if (mSettings.mReadExternalStorageEnforced == null
22927                        || mSettings.mReadExternalStorageEnforced != enforced) {
22928                    mSettings.mReadExternalStorageEnforced =
22929                            enforced ? Boolean.TRUE : Boolean.FALSE;
22930                    mSettings.writeLPr();
22931                }
22932            }
22933            // kill any non-foreground processes so we restart them and
22934            // grant/revoke the GID.
22935            final IActivityManager am = ActivityManager.getService();
22936            if (am != null) {
22937                final long token = Binder.clearCallingIdentity();
22938                try {
22939                    am.killProcessesBelowForeground("setPermissionEnforcement");
22940                } catch (RemoteException e) {
22941                } finally {
22942                    Binder.restoreCallingIdentity(token);
22943                }
22944            }
22945        } else {
22946            throw new IllegalArgumentException("No selective enforcement for " + permission);
22947        }
22948    }
22949
22950    @Override
22951    @Deprecated
22952    public boolean isPermissionEnforced(String permission) {
22953        // allow instant applications
22954        return true;
22955    }
22956
22957    @Override
22958    public boolean isStorageLow() {
22959        // allow instant applications
22960        final long token = Binder.clearCallingIdentity();
22961        try {
22962            final DeviceStorageMonitorInternal
22963                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22964            if (dsm != null) {
22965                return dsm.isMemoryLow();
22966            } else {
22967                return false;
22968            }
22969        } finally {
22970            Binder.restoreCallingIdentity(token);
22971        }
22972    }
22973
22974    @Override
22975    public IPackageInstaller getPackageInstaller() {
22976        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
22977            return null;
22978        }
22979        return mInstallerService;
22980    }
22981
22982    @Override
22983    public IArtManager getArtManager() {
22984        return mArtManagerService;
22985    }
22986
22987    private boolean userNeedsBadging(int userId) {
22988        int index = mUserNeedsBadging.indexOfKey(userId);
22989        if (index < 0) {
22990            final UserInfo userInfo;
22991            final long token = Binder.clearCallingIdentity();
22992            try {
22993                userInfo = sUserManager.getUserInfo(userId);
22994            } finally {
22995                Binder.restoreCallingIdentity(token);
22996            }
22997            final boolean b;
22998            if (userInfo != null && userInfo.isManagedProfile()) {
22999                b = true;
23000            } else {
23001                b = false;
23002            }
23003            mUserNeedsBadging.put(userId, b);
23004            return b;
23005        }
23006        return mUserNeedsBadging.valueAt(index);
23007    }
23008
23009    @Override
23010    public KeySet getKeySetByAlias(String packageName, String alias) {
23011        if (packageName == null || alias == null) {
23012            return null;
23013        }
23014        synchronized(mPackages) {
23015            final PackageParser.Package pkg = mPackages.get(packageName);
23016            if (pkg == null) {
23017                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23018                throw new IllegalArgumentException("Unknown package: " + packageName);
23019            }
23020            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23021            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
23022                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
23023                throw new IllegalArgumentException("Unknown package: " + packageName);
23024            }
23025            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23026            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
23027        }
23028    }
23029
23030    @Override
23031    public KeySet getSigningKeySet(String packageName) {
23032        if (packageName == null) {
23033            return null;
23034        }
23035        synchronized(mPackages) {
23036            final int callingUid = Binder.getCallingUid();
23037            final int callingUserId = UserHandle.getUserId(callingUid);
23038            final PackageParser.Package pkg = mPackages.get(packageName);
23039            if (pkg == null) {
23040                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23041                throw new IllegalArgumentException("Unknown package: " + packageName);
23042            }
23043            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23044            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
23045                // filter and pretend the package doesn't exist
23046                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
23047                        + ", uid:" + callingUid);
23048                throw new IllegalArgumentException("Unknown package: " + packageName);
23049            }
23050            if (pkg.applicationInfo.uid != callingUid
23051                    && Process.SYSTEM_UID != callingUid) {
23052                throw new SecurityException("May not access signing KeySet of other apps.");
23053            }
23054            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23055            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
23056        }
23057    }
23058
23059    @Override
23060    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
23061        final int callingUid = Binder.getCallingUid();
23062        if (getInstantAppPackageName(callingUid) != null) {
23063            return false;
23064        }
23065        if (packageName == null || ks == null) {
23066            return false;
23067        }
23068        synchronized(mPackages) {
23069            final PackageParser.Package pkg = mPackages.get(packageName);
23070            if (pkg == null
23071                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23072                            UserHandle.getUserId(callingUid))) {
23073                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23074                throw new IllegalArgumentException("Unknown package: " + packageName);
23075            }
23076            IBinder ksh = ks.getToken();
23077            if (ksh instanceof KeySetHandle) {
23078                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23079                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23080            }
23081            return false;
23082        }
23083    }
23084
23085    @Override
23086    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23087        final int callingUid = Binder.getCallingUid();
23088        if (getInstantAppPackageName(callingUid) != null) {
23089            return false;
23090        }
23091        if (packageName == null || ks == null) {
23092            return false;
23093        }
23094        synchronized(mPackages) {
23095            final PackageParser.Package pkg = mPackages.get(packageName);
23096            if (pkg == null
23097                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23098                            UserHandle.getUserId(callingUid))) {
23099                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23100                throw new IllegalArgumentException("Unknown package: " + packageName);
23101            }
23102            IBinder ksh = ks.getToken();
23103            if (ksh instanceof KeySetHandle) {
23104                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23105                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23106            }
23107            return false;
23108        }
23109    }
23110
23111    private void deletePackageIfUnusedLPr(final String packageName) {
23112        PackageSetting ps = mSettings.mPackages.get(packageName);
23113        if (ps == null) {
23114            return;
23115        }
23116        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23117            // TODO Implement atomic delete if package is unused
23118            // It is currently possible that the package will be deleted even if it is installed
23119            // after this method returns.
23120            mHandler.post(new Runnable() {
23121                public void run() {
23122                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23123                            0, PackageManager.DELETE_ALL_USERS);
23124                }
23125            });
23126        }
23127    }
23128
23129    /**
23130     * Check and throw if the given before/after packages would be considered a
23131     * downgrade.
23132     */
23133    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23134            throws PackageManagerException {
23135        if (after.getLongVersionCode() < before.getLongVersionCode()) {
23136            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23137                    "Update version code " + after.versionCode + " is older than current "
23138                    + before.getLongVersionCode());
23139        } else if (after.getLongVersionCode() == before.getLongVersionCode()) {
23140            if (after.baseRevisionCode < before.baseRevisionCode) {
23141                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23142                        "Update base revision code " + after.baseRevisionCode
23143                        + " is older than current " + before.baseRevisionCode);
23144            }
23145
23146            if (!ArrayUtils.isEmpty(after.splitNames)) {
23147                for (int i = 0; i < after.splitNames.length; i++) {
23148                    final String splitName = after.splitNames[i];
23149                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23150                    if (j != -1) {
23151                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23152                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23153                                    "Update split " + splitName + " revision code "
23154                                    + after.splitRevisionCodes[i] + " is older than current "
23155                                    + before.splitRevisionCodes[j]);
23156                        }
23157                    }
23158                }
23159            }
23160        }
23161    }
23162
23163    private static class MoveCallbacks extends Handler {
23164        private static final int MSG_CREATED = 1;
23165        private static final int MSG_STATUS_CHANGED = 2;
23166
23167        private final RemoteCallbackList<IPackageMoveObserver>
23168                mCallbacks = new RemoteCallbackList<>();
23169
23170        private final SparseIntArray mLastStatus = new SparseIntArray();
23171
23172        public MoveCallbacks(Looper looper) {
23173            super(looper);
23174        }
23175
23176        public void register(IPackageMoveObserver callback) {
23177            mCallbacks.register(callback);
23178        }
23179
23180        public void unregister(IPackageMoveObserver callback) {
23181            mCallbacks.unregister(callback);
23182        }
23183
23184        @Override
23185        public void handleMessage(Message msg) {
23186            final SomeArgs args = (SomeArgs) msg.obj;
23187            final int n = mCallbacks.beginBroadcast();
23188            for (int i = 0; i < n; i++) {
23189                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23190                try {
23191                    invokeCallback(callback, msg.what, args);
23192                } catch (RemoteException ignored) {
23193                }
23194            }
23195            mCallbacks.finishBroadcast();
23196            args.recycle();
23197        }
23198
23199        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23200                throws RemoteException {
23201            switch (what) {
23202                case MSG_CREATED: {
23203                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23204                    break;
23205                }
23206                case MSG_STATUS_CHANGED: {
23207                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23208                    break;
23209                }
23210            }
23211        }
23212
23213        private void notifyCreated(int moveId, Bundle extras) {
23214            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23215
23216            final SomeArgs args = SomeArgs.obtain();
23217            args.argi1 = moveId;
23218            args.arg2 = extras;
23219            obtainMessage(MSG_CREATED, args).sendToTarget();
23220        }
23221
23222        private void notifyStatusChanged(int moveId, int status) {
23223            notifyStatusChanged(moveId, status, -1);
23224        }
23225
23226        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23227            Slog.v(TAG, "Move " + moveId + " status " + status);
23228
23229            final SomeArgs args = SomeArgs.obtain();
23230            args.argi1 = moveId;
23231            args.argi2 = status;
23232            args.arg3 = estMillis;
23233            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23234
23235            synchronized (mLastStatus) {
23236                mLastStatus.put(moveId, status);
23237            }
23238        }
23239    }
23240
23241    private final static class OnPermissionChangeListeners extends Handler {
23242        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23243
23244        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23245                new RemoteCallbackList<>();
23246
23247        public OnPermissionChangeListeners(Looper looper) {
23248            super(looper);
23249        }
23250
23251        @Override
23252        public void handleMessage(Message msg) {
23253            switch (msg.what) {
23254                case MSG_ON_PERMISSIONS_CHANGED: {
23255                    final int uid = msg.arg1;
23256                    handleOnPermissionsChanged(uid);
23257                } break;
23258            }
23259        }
23260
23261        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23262            mPermissionListeners.register(listener);
23263
23264        }
23265
23266        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23267            mPermissionListeners.unregister(listener);
23268        }
23269
23270        public void onPermissionsChanged(int uid) {
23271            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23272                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23273            }
23274        }
23275
23276        private void handleOnPermissionsChanged(int uid) {
23277            final int count = mPermissionListeners.beginBroadcast();
23278            try {
23279                for (int i = 0; i < count; i++) {
23280                    IOnPermissionsChangeListener callback = mPermissionListeners
23281                            .getBroadcastItem(i);
23282                    try {
23283                        callback.onPermissionsChanged(uid);
23284                    } catch (RemoteException e) {
23285                        Log.e(TAG, "Permission listener is dead", e);
23286                    }
23287                }
23288            } finally {
23289                mPermissionListeners.finishBroadcast();
23290            }
23291        }
23292    }
23293
23294    private class PackageManagerNative extends IPackageManagerNative.Stub {
23295        @Override
23296        public String[] getNamesForUids(int[] uids) throws RemoteException {
23297            final String[] results = PackageManagerService.this.getNamesForUids(uids);
23298            // massage results so they can be parsed by the native binder
23299            for (int i = results.length - 1; i >= 0; --i) {
23300                if (results[i] == null) {
23301                    results[i] = "";
23302                }
23303            }
23304            return results;
23305        }
23306
23307        // NB: this differentiates between preloads and sideloads
23308        @Override
23309        public String getInstallerForPackage(String packageName) throws RemoteException {
23310            final String installerName = getInstallerPackageName(packageName);
23311            if (!TextUtils.isEmpty(installerName)) {
23312                return installerName;
23313            }
23314            // differentiate between preload and sideload
23315            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23316            ApplicationInfo appInfo = getApplicationInfo(packageName,
23317                                    /*flags*/ 0,
23318                                    /*userId*/ callingUser);
23319            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23320                return "preload";
23321            }
23322            return "";
23323        }
23324
23325        @Override
23326        public long getVersionCodeForPackage(String packageName) throws RemoteException {
23327            try {
23328                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23329                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
23330                if (pInfo != null) {
23331                    return pInfo.getLongVersionCode();
23332                }
23333            } catch (Exception e) {
23334            }
23335            return 0;
23336        }
23337    }
23338
23339    private class PackageManagerInternalImpl extends PackageManagerInternal {
23340        @Override
23341        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
23342                int flagValues, int userId) {
23343            PackageManagerService.this.updatePermissionFlags(
23344                    permName, packageName, flagMask, flagValues, userId);
23345        }
23346
23347        @Override
23348        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
23349            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
23350        }
23351
23352        @Override
23353        public boolean isInstantApp(String packageName, int userId) {
23354            return PackageManagerService.this.isInstantApp(packageName, userId);
23355        }
23356
23357        @Override
23358        public String getInstantAppPackageName(int uid) {
23359            return PackageManagerService.this.getInstantAppPackageName(uid);
23360        }
23361
23362        @Override
23363        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
23364            synchronized (mPackages) {
23365                return PackageManagerService.this.filterAppAccessLPr(
23366                        (PackageSetting) pkg.mExtras, callingUid, userId);
23367            }
23368        }
23369
23370        @Override
23371        public PackageParser.Package getPackage(String packageName) {
23372            synchronized (mPackages) {
23373                packageName = resolveInternalPackageNameLPr(
23374                        packageName, PackageManager.VERSION_CODE_HIGHEST);
23375                return mPackages.get(packageName);
23376            }
23377        }
23378
23379        @Override
23380        public PackageList getPackageList(PackageListObserver observer) {
23381            synchronized (mPackages) {
23382                final int N = mPackages.size();
23383                final ArrayList<String> list = new ArrayList<>(N);
23384                for (int i = 0; i < N; i++) {
23385                    list.add(mPackages.keyAt(i));
23386                }
23387                final PackageList packageList = new PackageList(list, observer);
23388                if (observer != null) {
23389                    mPackageListObservers.add(packageList);
23390                }
23391                return packageList;
23392            }
23393        }
23394
23395        @Override
23396        public void removePackageListObserver(PackageListObserver observer) {
23397            synchronized (mPackages) {
23398                mPackageListObservers.remove(observer);
23399            }
23400        }
23401
23402        @Override
23403        public PackageParser.Package getDisabledPackage(String packageName) {
23404            synchronized (mPackages) {
23405                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
23406                return (ps != null) ? ps.pkg : null;
23407            }
23408        }
23409
23410        @Override
23411        public String getKnownPackageName(int knownPackage, int userId) {
23412            switch(knownPackage) {
23413                case PackageManagerInternal.PACKAGE_BROWSER:
23414                    return getDefaultBrowserPackageName(userId);
23415                case PackageManagerInternal.PACKAGE_INSTALLER:
23416                    return mRequiredInstallerPackage;
23417                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
23418                    return mSetupWizardPackage;
23419                case PackageManagerInternal.PACKAGE_SYSTEM:
23420                    return "android";
23421                case PackageManagerInternal.PACKAGE_VERIFIER:
23422                    return mRequiredVerifierPackage;
23423            }
23424            return null;
23425        }
23426
23427        @Override
23428        public boolean isResolveActivityComponent(ComponentInfo component) {
23429            return mResolveActivity.packageName.equals(component.packageName)
23430                    && mResolveActivity.name.equals(component.name);
23431        }
23432
23433        @Override
23434        public void setLocationPackagesProvider(PackagesProvider provider) {
23435            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
23436        }
23437
23438        @Override
23439        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23440            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
23441        }
23442
23443        @Override
23444        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23445            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
23446        }
23447
23448        @Override
23449        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23450            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
23451        }
23452
23453        @Override
23454        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23455            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
23456        }
23457
23458        @Override
23459        public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) {
23460            mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider);
23461        }
23462
23463        @Override
23464        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23465            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
23466        }
23467
23468        @Override
23469        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23470            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
23471        }
23472
23473        @Override
23474        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23475            synchronized (mPackages) {
23476                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23477            }
23478            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
23479        }
23480
23481        @Override
23482        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23483            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
23484                    packageName, userId);
23485        }
23486
23487        @Override
23488        public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) {
23489            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp(
23490                    packageName, userId);
23491        }
23492
23493        @Override
23494        public void setKeepUninstalledPackages(final List<String> packageList) {
23495            Preconditions.checkNotNull(packageList);
23496            List<String> removedFromList = null;
23497            synchronized (mPackages) {
23498                if (mKeepUninstalledPackages != null) {
23499                    final int packagesCount = mKeepUninstalledPackages.size();
23500                    for (int i = 0; i < packagesCount; i++) {
23501                        String oldPackage = mKeepUninstalledPackages.get(i);
23502                        if (packageList != null && packageList.contains(oldPackage)) {
23503                            continue;
23504                        }
23505                        if (removedFromList == null) {
23506                            removedFromList = new ArrayList<>();
23507                        }
23508                        removedFromList.add(oldPackage);
23509                    }
23510                }
23511                mKeepUninstalledPackages = new ArrayList<>(packageList);
23512                if (removedFromList != null) {
23513                    final int removedCount = removedFromList.size();
23514                    for (int i = 0; i < removedCount; i++) {
23515                        deletePackageIfUnusedLPr(removedFromList.get(i));
23516                    }
23517                }
23518            }
23519        }
23520
23521        @Override
23522        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23523            synchronized (mPackages) {
23524                return mPermissionManager.isPermissionsReviewRequired(
23525                        mPackages.get(packageName), userId);
23526            }
23527        }
23528
23529        @Override
23530        public PackageInfo getPackageInfo(
23531                String packageName, int flags, int filterCallingUid, int userId) {
23532            return PackageManagerService.this
23533                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
23534                            flags, filterCallingUid, userId);
23535        }
23536
23537        @Override
23538        public int getPackageUid(String packageName, int flags, int userId) {
23539            return PackageManagerService.this
23540                    .getPackageUid(packageName, flags, userId);
23541        }
23542
23543        @Override
23544        public ApplicationInfo getApplicationInfo(
23545                String packageName, int flags, int filterCallingUid, int userId) {
23546            return PackageManagerService.this
23547                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
23548        }
23549
23550        @Override
23551        public ActivityInfo getActivityInfo(
23552                ComponentName component, int flags, int filterCallingUid, int userId) {
23553            return PackageManagerService.this
23554                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
23555        }
23556
23557        @Override
23558        public List<ResolveInfo> queryIntentActivities(
23559                Intent intent, int flags, int filterCallingUid, int userId) {
23560            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23561            return PackageManagerService.this
23562                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
23563                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
23564        }
23565
23566        @Override
23567        public List<ResolveInfo> queryIntentServices(
23568                Intent intent, int flags, int callingUid, int userId) {
23569            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23570            return PackageManagerService.this
23571                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
23572                            false);
23573        }
23574
23575        @Override
23576        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23577                int userId) {
23578            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23579        }
23580
23581        @Override
23582        public void setDeviceAndProfileOwnerPackages(
23583                int deviceOwnerUserId, String deviceOwnerPackage,
23584                SparseArray<String> profileOwnerPackages) {
23585            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23586                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23587        }
23588
23589        @Override
23590        public boolean isPackageDataProtected(int userId, String packageName) {
23591            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23592        }
23593
23594        @Override
23595        public boolean isPackageEphemeral(int userId, String packageName) {
23596            synchronized (mPackages) {
23597                final PackageSetting ps = mSettings.mPackages.get(packageName);
23598                return ps != null ? ps.getInstantApp(userId) : false;
23599            }
23600        }
23601
23602        @Override
23603        public boolean wasPackageEverLaunched(String packageName, int userId) {
23604            synchronized (mPackages) {
23605                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23606            }
23607        }
23608
23609        @Override
23610        public void grantRuntimePermission(String packageName, String permName, int userId,
23611                boolean overridePolicy) {
23612            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
23613                    permName, packageName, overridePolicy, getCallingUid(), userId,
23614                    mPermissionCallback);
23615        }
23616
23617        @Override
23618        public void revokeRuntimePermission(String packageName, String permName, int userId,
23619                boolean overridePolicy) {
23620            mPermissionManager.revokeRuntimePermission(
23621                    permName, packageName, overridePolicy, getCallingUid(), userId,
23622                    mPermissionCallback);
23623        }
23624
23625        @Override
23626        public String getNameForUid(int uid) {
23627            return PackageManagerService.this.getNameForUid(uid);
23628        }
23629
23630        @Override
23631        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23632                Intent origIntent, String resolvedType, String callingPackage,
23633                Bundle verificationBundle, int userId) {
23634            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23635                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
23636                    userId);
23637        }
23638
23639        @Override
23640        public void grantEphemeralAccess(int userId, Intent intent,
23641                int targetAppId, int ephemeralAppId) {
23642            synchronized (mPackages) {
23643                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23644                        targetAppId, ephemeralAppId);
23645            }
23646        }
23647
23648        @Override
23649        public boolean isInstantAppInstallerComponent(ComponentName component) {
23650            synchronized (mPackages) {
23651                return mInstantAppInstallerActivity != null
23652                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23653            }
23654        }
23655
23656        @Override
23657        public void pruneInstantApps() {
23658            mInstantAppRegistry.pruneInstantApps();
23659        }
23660
23661        @Override
23662        public String getSetupWizardPackageName() {
23663            return mSetupWizardPackage;
23664        }
23665
23666        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23667            if (policy != null) {
23668                mExternalSourcesPolicy = policy;
23669            }
23670        }
23671
23672        @Override
23673        public boolean isPackagePersistent(String packageName) {
23674            synchronized (mPackages) {
23675                PackageParser.Package pkg = mPackages.get(packageName);
23676                return pkg != null
23677                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23678                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23679                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23680                        : false;
23681            }
23682        }
23683
23684        @Override
23685        public boolean isLegacySystemApp(Package pkg) {
23686            synchronized (mPackages) {
23687                final PackageSetting ps = (PackageSetting) pkg.mExtras;
23688                return mPromoteSystemApps
23689                        && ps.isSystem()
23690                        && mExistingSystemPackages.contains(ps.name);
23691            }
23692        }
23693
23694        @Override
23695        public List<PackageInfo> getOverlayPackages(int userId) {
23696            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23697            synchronized (mPackages) {
23698                for (PackageParser.Package p : mPackages.values()) {
23699                    if (p.mOverlayTarget != null) {
23700                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23701                        if (pkg != null) {
23702                            overlayPackages.add(pkg);
23703                        }
23704                    }
23705                }
23706            }
23707            return overlayPackages;
23708        }
23709
23710        @Override
23711        public List<String> getTargetPackageNames(int userId) {
23712            List<String> targetPackages = new ArrayList<>();
23713            synchronized (mPackages) {
23714                for (PackageParser.Package p : mPackages.values()) {
23715                    if (p.mOverlayTarget == null) {
23716                        targetPackages.add(p.packageName);
23717                    }
23718                }
23719            }
23720            return targetPackages;
23721        }
23722
23723        @Override
23724        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23725                @Nullable List<String> overlayPackageNames) {
23726            synchronized (mPackages) {
23727                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23728                    Slog.e(TAG, "failed to find package " + targetPackageName);
23729                    return false;
23730                }
23731                ArrayList<String> overlayPaths = null;
23732                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
23733                    final int N = overlayPackageNames.size();
23734                    overlayPaths = new ArrayList<>(N);
23735                    for (int i = 0; i < N; i++) {
23736                        final String packageName = overlayPackageNames.get(i);
23737                        final PackageParser.Package pkg = mPackages.get(packageName);
23738                        if (pkg == null) {
23739                            Slog.e(TAG, "failed to find package " + packageName);
23740                            return false;
23741                        }
23742                        overlayPaths.add(pkg.baseCodePath);
23743                    }
23744                }
23745
23746                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
23747                ps.setOverlayPaths(overlayPaths, userId);
23748                return true;
23749            }
23750        }
23751
23752        @Override
23753        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23754                int flags, int userId, boolean resolveForStart) {
23755            return resolveIntentInternal(
23756                    intent, resolvedType, flags, userId, resolveForStart);
23757        }
23758
23759        @Override
23760        public ResolveInfo resolveService(Intent intent, String resolvedType,
23761                int flags, int userId, int callingUid) {
23762            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
23763        }
23764
23765        @Override
23766        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
23767            return PackageManagerService.this.resolveContentProviderInternal(
23768                    name, flags, userId);
23769        }
23770
23771        @Override
23772        public void addIsolatedUid(int isolatedUid, int ownerUid) {
23773            synchronized (mPackages) {
23774                mIsolatedOwners.put(isolatedUid, ownerUid);
23775            }
23776        }
23777
23778        @Override
23779        public void removeIsolatedUid(int isolatedUid) {
23780            synchronized (mPackages) {
23781                mIsolatedOwners.delete(isolatedUid);
23782            }
23783        }
23784
23785        @Override
23786        public int getUidTargetSdkVersion(int uid) {
23787            synchronized (mPackages) {
23788                return getUidTargetSdkVersionLockedLPr(uid);
23789            }
23790        }
23791
23792        @Override
23793        public int getPackageTargetSdkVersion(String packageName) {
23794            synchronized (mPackages) {
23795                return getPackageTargetSdkVersionLockedLPr(packageName);
23796            }
23797        }
23798
23799        @Override
23800        public boolean canAccessInstantApps(int callingUid, int userId) {
23801            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
23802        }
23803
23804        @Override
23805        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
23806            synchronized (mPackages) {
23807                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
23808            }
23809        }
23810
23811        @Override
23812        public void notifyPackageUse(String packageName, int reason) {
23813            synchronized (mPackages) {
23814                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
23815            }
23816        }
23817    }
23818
23819    @Override
23820    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23821        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23822        synchronized (mPackages) {
23823            final long identity = Binder.clearCallingIdentity();
23824            try {
23825                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
23826                        packageNames, userId);
23827            } finally {
23828                Binder.restoreCallingIdentity(identity);
23829            }
23830        }
23831    }
23832
23833    @Override
23834    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23835        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23836        synchronized (mPackages) {
23837            final long identity = Binder.clearCallingIdentity();
23838            try {
23839                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
23840                        packageNames, userId);
23841            } finally {
23842                Binder.restoreCallingIdentity(identity);
23843            }
23844        }
23845    }
23846
23847    private static void enforceSystemOrPhoneCaller(String tag) {
23848        int callingUid = Binder.getCallingUid();
23849        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23850            throw new SecurityException(
23851                    "Cannot call " + tag + " from UID " + callingUid);
23852        }
23853    }
23854
23855    boolean isHistoricalPackageUsageAvailable() {
23856        return mPackageUsage.isHistoricalPackageUsageAvailable();
23857    }
23858
23859    /**
23860     * Return a <b>copy</b> of the collection of packages known to the package manager.
23861     * @return A copy of the values of mPackages.
23862     */
23863    Collection<PackageParser.Package> getPackages() {
23864        synchronized (mPackages) {
23865            return new ArrayList<>(mPackages.values());
23866        }
23867    }
23868
23869    /**
23870     * Logs process start information (including base APK hash) to the security log.
23871     * @hide
23872     */
23873    @Override
23874    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23875            String apkFile, int pid) {
23876        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23877            return;
23878        }
23879        if (!SecurityLog.isLoggingEnabled()) {
23880            return;
23881        }
23882        Bundle data = new Bundle();
23883        data.putLong("startTimestamp", System.currentTimeMillis());
23884        data.putString("processName", processName);
23885        data.putInt("uid", uid);
23886        data.putString("seinfo", seinfo);
23887        data.putString("apkFile", apkFile);
23888        data.putInt("pid", pid);
23889        Message msg = mProcessLoggingHandler.obtainMessage(
23890                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23891        msg.setData(data);
23892        mProcessLoggingHandler.sendMessage(msg);
23893    }
23894
23895    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23896        return mCompilerStats.getPackageStats(pkgName);
23897    }
23898
23899    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23900        return getOrCreateCompilerPackageStats(pkg.packageName);
23901    }
23902
23903    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23904        return mCompilerStats.getOrCreatePackageStats(pkgName);
23905    }
23906
23907    public void deleteCompilerPackageStats(String pkgName) {
23908        mCompilerStats.deletePackageStats(pkgName);
23909    }
23910
23911    @Override
23912    public int getInstallReason(String packageName, int userId) {
23913        final int callingUid = Binder.getCallingUid();
23914        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
23915                true /* requireFullPermission */, false /* checkShell */,
23916                "get install reason");
23917        synchronized (mPackages) {
23918            final PackageSetting ps = mSettings.mPackages.get(packageName);
23919            if (filterAppAccessLPr(ps, callingUid, userId)) {
23920                return PackageManager.INSTALL_REASON_UNKNOWN;
23921            }
23922            if (ps != null) {
23923                return ps.getInstallReason(userId);
23924            }
23925        }
23926        return PackageManager.INSTALL_REASON_UNKNOWN;
23927    }
23928
23929    @Override
23930    public boolean canRequestPackageInstalls(String packageName, int userId) {
23931        return canRequestPackageInstallsInternal(packageName, 0, userId,
23932                true /* throwIfPermNotDeclared*/);
23933    }
23934
23935    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
23936            boolean throwIfPermNotDeclared) {
23937        int callingUid = Binder.getCallingUid();
23938        int uid = getPackageUid(packageName, 0, userId);
23939        if (callingUid != uid && callingUid != Process.ROOT_UID
23940                && callingUid != Process.SYSTEM_UID) {
23941            throw new SecurityException(
23942                    "Caller uid " + callingUid + " does not own package " + packageName);
23943        }
23944        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
23945        if (info == null) {
23946            return false;
23947        }
23948        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23949            return false;
23950        }
23951        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23952        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23953        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23954            if (throwIfPermNotDeclared) {
23955                throw new SecurityException("Need to declare " + appOpPermission
23956                        + " to call this api");
23957            } else {
23958                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
23959                return false;
23960            }
23961        }
23962        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23963            return false;
23964        }
23965        if (mExternalSourcesPolicy != null) {
23966            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23967            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23968                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23969            }
23970        }
23971        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23972    }
23973
23974    @Override
23975    public ComponentName getInstantAppResolverSettingsComponent() {
23976        return mInstantAppResolverSettingsComponent;
23977    }
23978
23979    @Override
23980    public ComponentName getInstantAppInstallerComponent() {
23981        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23982            return null;
23983        }
23984        return mInstantAppInstallerActivity == null
23985                ? null : mInstantAppInstallerActivity.getComponentName();
23986    }
23987
23988    @Override
23989    public String getInstantAppAndroidId(String packageName, int userId) {
23990        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
23991                "getInstantAppAndroidId");
23992        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
23993                true /* requireFullPermission */, false /* checkShell */,
23994                "getInstantAppAndroidId");
23995        // Make sure the target is an Instant App.
23996        if (!isInstantApp(packageName, userId)) {
23997            return null;
23998        }
23999        synchronized (mPackages) {
24000            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24001        }
24002    }
24003
24004    boolean canHaveOatDir(String packageName) {
24005        synchronized (mPackages) {
24006            PackageParser.Package p = mPackages.get(packageName);
24007            if (p == null) {
24008                return false;
24009            }
24010            return p.canHaveOatDir();
24011        }
24012    }
24013
24014    private String getOatDir(PackageParser.Package pkg) {
24015        if (!pkg.canHaveOatDir()) {
24016            return null;
24017        }
24018        File codePath = new File(pkg.codePath);
24019        if (codePath.isDirectory()) {
24020            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
24021        }
24022        return null;
24023    }
24024
24025    void deleteOatArtifactsOfPackage(String packageName) {
24026        final String[] instructionSets;
24027        final List<String> codePaths;
24028        final String oatDir;
24029        final PackageParser.Package pkg;
24030        synchronized (mPackages) {
24031            pkg = mPackages.get(packageName);
24032        }
24033        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
24034        codePaths = pkg.getAllCodePaths();
24035        oatDir = getOatDir(pkg);
24036
24037        for (String codePath : codePaths) {
24038            for (String isa : instructionSets) {
24039                try {
24040                    mInstaller.deleteOdex(codePath, isa, oatDir);
24041                } catch (InstallerException e) {
24042                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
24043                }
24044            }
24045        }
24046    }
24047
24048    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
24049        Set<String> unusedPackages = new HashSet<>();
24050        long currentTimeInMillis = System.currentTimeMillis();
24051        synchronized (mPackages) {
24052            for (PackageParser.Package pkg : mPackages.values()) {
24053                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
24054                if (ps == null) {
24055                    continue;
24056                }
24057                PackageDexUsage.PackageUseInfo packageUseInfo =
24058                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
24059                if (PackageManagerServiceUtils
24060                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
24061                                downgradeTimeThresholdMillis, packageUseInfo,
24062                                pkg.getLatestPackageUseTimeInMills(),
24063                                pkg.getLatestForegroundPackageUseTimeInMills())) {
24064                    unusedPackages.add(pkg.packageName);
24065                }
24066            }
24067        }
24068        return unusedPackages;
24069    }
24070
24071    @Override
24072    public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning,
24073            int userId) {
24074        final int callingUid = Binder.getCallingUid();
24075        final int callingAppId = UserHandle.getAppId(callingUid);
24076
24077        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24078                true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo");
24079
24080        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24081                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24082            throw new SecurityException("Caller must have the "
24083                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24084        }
24085
24086        synchronized(mPackages) {
24087            mSettings.setHarmfulAppWarningLPw(packageName, warning, userId);
24088            scheduleWritePackageRestrictionsLocked(userId);
24089        }
24090    }
24091
24092    @Nullable
24093    @Override
24094    public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) {
24095        final int callingUid = Binder.getCallingUid();
24096        final int callingAppId = UserHandle.getAppId(callingUid);
24097
24098        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24099                true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo");
24100
24101        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24102                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24103            throw new SecurityException("Caller must have the "
24104                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24105        }
24106
24107        synchronized(mPackages) {
24108            return mSettings.getHarmfulAppWarningLPr(packageName, userId);
24109        }
24110    }
24111}
24112
24113interface PackageSender {
24114    /**
24115     * @param userIds User IDs where the action occurred on a full application
24116     * @param instantUserIds User IDs where the action occurred on an instant application
24117     */
24118    void sendPackageBroadcast(final String action, final String pkg,
24119        final Bundle extras, final int flags, final String targetPkg,
24120        final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds);
24121    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
24122        boolean includeStopped, int appId, int[] userIds, int[] instantUserIds);
24123    void notifyPackageAdded(String packageName);
24124    void notifyPackageRemoved(String packageName);
24125}
24126