PackageManagerService.java revision 1e423b950abc044d2f18a1771af19e42a5ea2022
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.INSTALL_PACKAGES;
21import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS;
22import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
23import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
25import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
31import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
39import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_NEWER_SDK;
51import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
52import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE;
54import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
55import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
56import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
57import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
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.verifySignatures;
112import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_FAILURE;
113import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS;
114import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
115
116import android.Manifest;
117import android.annotation.IntDef;
118import android.annotation.NonNull;
119import android.annotation.Nullable;
120import android.app.ActivityManager;
121import android.app.AppOpsManager;
122import android.app.IActivityManager;
123import android.app.ResourcesManager;
124import android.app.admin.IDevicePolicyManager;
125import android.app.admin.SecurityLog;
126import android.app.backup.IBackupManager;
127import android.content.BroadcastReceiver;
128import android.content.ComponentName;
129import android.content.ContentResolver;
130import android.content.Context;
131import android.content.IIntentReceiver;
132import android.content.Intent;
133import android.content.IntentFilter;
134import android.content.IntentSender;
135import android.content.IntentSender.SendIntentException;
136import android.content.ServiceConnection;
137import android.content.pm.ActivityInfo;
138import android.content.pm.ApplicationInfo;
139import android.content.pm.AppsQueryHelper;
140import android.content.pm.AuxiliaryResolveInfo;
141import android.content.pm.ChangedPackages;
142import android.content.pm.ComponentInfo;
143import android.content.pm.FallbackCategoryProvider;
144import android.content.pm.FeatureInfo;
145import android.content.pm.IDexModuleRegisterCallback;
146import android.content.pm.IOnPermissionsChangeListener;
147import android.content.pm.IPackageDataObserver;
148import android.content.pm.IPackageDeleteObserver;
149import android.content.pm.IPackageDeleteObserver2;
150import android.content.pm.IPackageInstallObserver2;
151import android.content.pm.IPackageInstaller;
152import android.content.pm.IPackageManager;
153import android.content.pm.IPackageManagerNative;
154import android.content.pm.IPackageMoveObserver;
155import android.content.pm.IPackageStatsObserver;
156import android.content.pm.InstantAppInfo;
157import android.content.pm.InstantAppRequest;
158import android.content.pm.InstantAppResolveInfo;
159import android.content.pm.InstrumentationInfo;
160import android.content.pm.IntentFilterVerificationInfo;
161import android.content.pm.KeySet;
162import android.content.pm.PackageCleanItem;
163import android.content.pm.PackageInfo;
164import android.content.pm.PackageInfoLite;
165import android.content.pm.PackageInstaller;
166import android.content.pm.PackageList;
167import android.content.pm.PackageManager;
168import android.content.pm.PackageManagerInternal;
169import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
170import android.content.pm.PackageManager.PackageInfoFlags;
171import android.content.pm.PackageManagerInternal.PackageListObserver;
172import android.content.pm.PackageParser;
173import android.content.pm.PackageParser.ActivityIntentInfo;
174import android.content.pm.PackageParser.Package;
175import android.content.pm.PackageParser.PackageLite;
176import android.content.pm.PackageParser.PackageParserException;
177import android.content.pm.PackageParser.ParseFlags;
178import android.content.pm.PackageParser.ServiceIntentInfo;
179import android.content.pm.PackageStats;
180import android.content.pm.PackageUserState;
181import android.content.pm.ParceledListSlice;
182import android.content.pm.PermissionGroupInfo;
183import android.content.pm.PermissionInfo;
184import android.content.pm.ProviderInfo;
185import android.content.pm.ResolveInfo;
186import android.content.pm.ServiceInfo;
187import android.content.pm.SharedLibraryInfo;
188import android.content.pm.Signature;
189import android.content.pm.UserInfo;
190import android.content.pm.VerifierDeviceIdentity;
191import android.content.pm.VerifierInfo;
192import android.content.pm.VersionedPackage;
193import android.content.pm.dex.IArtManager;
194import android.content.res.Resources;
195import android.database.ContentObserver;
196import android.graphics.Bitmap;
197import android.hardware.display.DisplayManager;
198import android.net.Uri;
199import android.os.Binder;
200import android.os.Build;
201import android.os.Bundle;
202import android.os.Debug;
203import android.os.Environment;
204import android.os.Environment.UserEnvironment;
205import android.os.FileUtils;
206import android.os.Handler;
207import android.os.IBinder;
208import android.os.Looper;
209import android.os.Message;
210import android.os.Parcel;
211import android.os.ParcelFileDescriptor;
212import android.os.PatternMatcher;
213import android.os.Process;
214import android.os.RemoteCallbackList;
215import android.os.RemoteException;
216import android.os.ResultReceiver;
217import android.os.SELinux;
218import android.os.ServiceManager;
219import android.os.ShellCallback;
220import android.os.SystemClock;
221import android.os.SystemProperties;
222import android.os.Trace;
223import android.os.UserHandle;
224import android.os.UserManager;
225import android.os.UserManagerInternal;
226import android.os.storage.IStorageManager;
227import android.os.storage.StorageEventListener;
228import android.os.storage.StorageManager;
229import android.os.storage.StorageManagerInternal;
230import android.os.storage.VolumeInfo;
231import android.os.storage.VolumeRecord;
232import android.provider.Settings.Global;
233import android.provider.Settings.Secure;
234import android.security.KeyStore;
235import android.security.SystemKeyStore;
236import android.service.pm.PackageServiceDumpProto;
237import android.system.ErrnoException;
238import android.system.Os;
239import android.text.TextUtils;
240import android.text.format.DateUtils;
241import android.util.ArrayMap;
242import android.util.ArraySet;
243import android.util.Base64;
244import android.util.DisplayMetrics;
245import android.util.EventLog;
246import android.util.ExceptionUtils;
247import android.util.Log;
248import android.util.LogPrinter;
249import android.util.LongSparseArray;
250import android.util.LongSparseLongArray;
251import android.util.MathUtils;
252import android.util.PackageUtils;
253import android.util.Pair;
254import android.util.PrintStreamPrinter;
255import android.util.Slog;
256import android.util.SparseArray;
257import android.util.SparseBooleanArray;
258import android.util.SparseIntArray;
259import android.util.TimingsTraceLog;
260import android.util.Xml;
261import android.util.jar.StrictJarFile;
262import android.util.proto.ProtoOutputStream;
263import android.view.Display;
264
265import com.android.internal.R;
266import com.android.internal.annotations.GuardedBy;
267import com.android.internal.app.IMediaContainerService;
268import com.android.internal.app.ResolverActivity;
269import com.android.internal.content.NativeLibraryHelper;
270import com.android.internal.content.PackageHelper;
271import com.android.internal.logging.MetricsLogger;
272import com.android.internal.os.IParcelFileDescriptorFactory;
273import com.android.internal.os.SomeArgs;
274import com.android.internal.os.Zygote;
275import com.android.internal.telephony.CarrierAppUtils;
276import com.android.internal.util.ArrayUtils;
277import com.android.internal.util.ConcurrentUtils;
278import com.android.internal.util.DumpUtils;
279import com.android.internal.util.FastXmlSerializer;
280import com.android.internal.util.IndentingPrintWriter;
281import com.android.internal.util.Preconditions;
282import com.android.internal.util.XmlUtils;
283import com.android.server.AttributeCache;
284import com.android.server.DeviceIdleController;
285import com.android.server.EventLogTags;
286import com.android.server.FgThread;
287import com.android.server.IntentResolver;
288import com.android.server.LocalServices;
289import com.android.server.LockGuard;
290import com.android.server.ServiceThread;
291import com.android.server.SystemConfig;
292import com.android.server.SystemServerInitThreadPool;
293import com.android.server.Watchdog;
294import com.android.server.net.NetworkPolicyManagerInternal;
295import com.android.server.pm.Installer.InstallerException;
296import com.android.server.pm.Settings.DatabaseVersion;
297import com.android.server.pm.Settings.VersionInfo;
298import com.android.server.pm.dex.ArtManagerService;
299import com.android.server.pm.dex.DexLogger;
300import com.android.server.pm.dex.DexManager;
301import com.android.server.pm.dex.DexoptOptions;
302import com.android.server.pm.dex.PackageDexUsage;
303import com.android.server.pm.permission.BasePermission;
304import com.android.server.pm.permission.DefaultPermissionGrantPolicy;
305import com.android.server.pm.permission.PermissionManagerService;
306import com.android.server.pm.permission.PermissionManagerInternal;
307import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback;
308import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback;
309import com.android.server.pm.permission.PermissionsState;
310import com.android.server.pm.permission.PermissionsState.PermissionState;
311import com.android.server.storage.DeviceStorageMonitorInternal;
312
313import dalvik.system.CloseGuard;
314import dalvik.system.VMRuntime;
315
316import libcore.io.IoUtils;
317
318import org.xmlpull.v1.XmlPullParser;
319import org.xmlpull.v1.XmlPullParserException;
320import org.xmlpull.v1.XmlSerializer;
321
322import java.io.BufferedOutputStream;
323import java.io.ByteArrayInputStream;
324import java.io.ByteArrayOutputStream;
325import java.io.File;
326import java.io.FileDescriptor;
327import java.io.FileInputStream;
328import java.io.FileOutputStream;
329import java.io.FilenameFilter;
330import java.io.IOException;
331import java.io.PrintWriter;
332import java.lang.annotation.Retention;
333import java.lang.annotation.RetentionPolicy;
334import java.nio.charset.StandardCharsets;
335import java.security.DigestInputStream;
336import java.security.MessageDigest;
337import java.security.NoSuchAlgorithmException;
338import java.security.PublicKey;
339import java.security.SecureRandom;
340import java.security.cert.Certificate;
341import java.security.cert.CertificateException;
342import java.util.ArrayList;
343import java.util.Arrays;
344import java.util.Collection;
345import java.util.Collections;
346import java.util.Comparator;
347import java.util.HashMap;
348import java.util.HashSet;
349import java.util.Iterator;
350import java.util.LinkedHashSet;
351import java.util.List;
352import java.util.Map;
353import java.util.Objects;
354import java.util.Set;
355import java.util.concurrent.CountDownLatch;
356import java.util.concurrent.Future;
357import java.util.concurrent.TimeUnit;
358import java.util.concurrent.atomic.AtomicBoolean;
359import java.util.concurrent.atomic.AtomicInteger;
360
361/**
362 * Keep track of all those APKs everywhere.
363 * <p>
364 * Internally there are two important locks:
365 * <ul>
366 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
367 * and other related state. It is a fine-grained lock that should only be held
368 * momentarily, as it's one of the most contended locks in the system.
369 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
370 * operations typically involve heavy lifting of application data on disk. Since
371 * {@code installd} is single-threaded, and it's operations can often be slow,
372 * this lock should never be acquired while already holding {@link #mPackages}.
373 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
374 * holding {@link #mInstallLock}.
375 * </ul>
376 * Many internal methods rely on the caller to hold the appropriate locks, and
377 * this contract is expressed through method name suffixes:
378 * <ul>
379 * <li>fooLI(): the caller must hold {@link #mInstallLock}
380 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
381 * being modified must be frozen
382 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
383 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
384 * </ul>
385 * <p>
386 * Because this class is very central to the platform's security; please run all
387 * CTS and unit tests whenever making modifications:
388 *
389 * <pre>
390 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
391 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
392 * </pre>
393 */
394public class PackageManagerService extends IPackageManager.Stub
395        implements PackageSender {
396    static final String TAG = "PackageManager";
397    public static final boolean DEBUG_SETTINGS = false;
398    static final boolean DEBUG_PREFERRED = false;
399    static final boolean DEBUG_UPGRADE = false;
400    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
401    private static final boolean DEBUG_BACKUP = false;
402    public static final boolean DEBUG_INSTALL = false;
403    public static final boolean DEBUG_REMOVE = false;
404    private static final boolean DEBUG_BROADCASTS = false;
405    private static final boolean DEBUG_SHOW_INFO = false;
406    private static final boolean DEBUG_PACKAGE_INFO = false;
407    private static final boolean DEBUG_INTENT_MATCHING = false;
408    public static final boolean DEBUG_PACKAGE_SCANNING = false;
409    private static final boolean DEBUG_VERIFY = false;
410    private static final boolean DEBUG_FILTERS = false;
411    public static final boolean DEBUG_PERMISSIONS = false;
412    private static final boolean DEBUG_SHARED_LIBRARIES = false;
413    public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
414
415    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
416    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
417    // user, but by default initialize to this.
418    public static final boolean DEBUG_DEXOPT = false;
419
420    private static final boolean DEBUG_ABI_SELECTION = false;
421    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
422    private static final boolean DEBUG_TRIAGED_MISSING = false;
423    private static final boolean DEBUG_APP_DATA = false;
424
425    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
426    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
427
428    private static final boolean HIDE_EPHEMERAL_APIS = false;
429
430    private static final boolean ENABLE_FREE_CACHE_V2 =
431            SystemProperties.getBoolean("fw.free_cache_v2", true);
432
433    private static final int RADIO_UID = Process.PHONE_UID;
434    private static final int LOG_UID = Process.LOG_UID;
435    private static final int NFC_UID = Process.NFC_UID;
436    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
437    private static final int SHELL_UID = Process.SHELL_UID;
438
439    // Suffix used during package installation when copying/moving
440    // package apks to install directory.
441    private static final String INSTALL_PACKAGE_SUFFIX = "-";
442
443    static final int SCAN_NO_DEX = 1<<0;
444    static final int SCAN_UPDATE_SIGNATURE = 1<<1;
445    static final int SCAN_NEW_INSTALL = 1<<2;
446    static final int SCAN_UPDATE_TIME = 1<<3;
447    static final int SCAN_BOOTING = 1<<4;
448    static final int SCAN_TRUSTED_OVERLAY = 1<<5;
449    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<6;
450    static final int SCAN_REQUIRE_KNOWN = 1<<7;
451    static final int SCAN_MOVE = 1<<8;
452    static final int SCAN_INITIAL = 1<<9;
453    static final int SCAN_CHECK_ONLY = 1<<10;
454    static final int SCAN_DONT_KILL_APP = 1<<11;
455    static final int SCAN_IGNORE_FROZEN = 1<<12;
456    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<13;
457    static final int SCAN_AS_INSTANT_APP = 1<<14;
458    static final int SCAN_AS_FULL_APP = 1<<15;
459    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<16;
460    static final int SCAN_AS_SYSTEM = 1<<17;
461    static final int SCAN_AS_PRIVILEGED = 1<<18;
462    static final int SCAN_AS_OEM = 1<<19;
463    static final int SCAN_AS_VENDOR = 1<<20;
464
465    @IntDef(flag = true, prefix = { "SCAN_" }, value = {
466            SCAN_NO_DEX,
467            SCAN_UPDATE_SIGNATURE,
468            SCAN_NEW_INSTALL,
469            SCAN_UPDATE_TIME,
470            SCAN_BOOTING,
471            SCAN_TRUSTED_OVERLAY,
472            SCAN_DELETE_DATA_ON_FAILURES,
473            SCAN_REQUIRE_KNOWN,
474            SCAN_MOVE,
475            SCAN_INITIAL,
476            SCAN_CHECK_ONLY,
477            SCAN_DONT_KILL_APP,
478            SCAN_IGNORE_FROZEN,
479            SCAN_FIRST_BOOT_OR_UPGRADE,
480            SCAN_AS_INSTANT_APP,
481            SCAN_AS_FULL_APP,
482            SCAN_AS_VIRTUAL_PRELOAD,
483    })
484    @Retention(RetentionPolicy.SOURCE)
485    public @interface ScanFlags {}
486
487    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
488    /** Extension of the compressed packages */
489    public final static String COMPRESSED_EXTENSION = ".gz";
490    /** Suffix of stub packages on the system partition */
491    public final static String STUB_SUFFIX = "-Stub";
492
493    private static final int[] EMPTY_INT_ARRAY = new int[0];
494
495    private static final int TYPE_UNKNOWN = 0;
496    private static final int TYPE_ACTIVITY = 1;
497    private static final int TYPE_RECEIVER = 2;
498    private static final int TYPE_SERVICE = 3;
499    private static final int TYPE_PROVIDER = 4;
500    @IntDef(prefix = { "TYPE_" }, value = {
501            TYPE_UNKNOWN,
502            TYPE_ACTIVITY,
503            TYPE_RECEIVER,
504            TYPE_SERVICE,
505            TYPE_PROVIDER,
506    })
507    @Retention(RetentionPolicy.SOURCE)
508    public @interface ComponentType {}
509
510    /**
511     * Timeout (in milliseconds) after which the watchdog should declare that
512     * our handler thread is wedged.  The usual default for such things is one
513     * minute but we sometimes do very lengthy I/O operations on this thread,
514     * such as installing multi-gigabyte applications, so ours needs to be longer.
515     */
516    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
517
518    /**
519     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
520     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
521     * settings entry if available, otherwise we use the hardcoded default.  If it's been
522     * more than this long since the last fstrim, we force one during the boot sequence.
523     *
524     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
525     * one gets run at the next available charging+idle time.  This final mandatory
526     * no-fstrim check kicks in only of the other scheduling criteria is never met.
527     */
528    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
529
530    /**
531     * Whether verification is enabled by default.
532     */
533    private static final boolean DEFAULT_VERIFY_ENABLE = true;
534
535    /**
536     * The default maximum time to wait for the verification agent to return in
537     * milliseconds.
538     */
539    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
540
541    /**
542     * The default response for package verification timeout.
543     *
544     * This can be either PackageManager.VERIFICATION_ALLOW or
545     * PackageManager.VERIFICATION_REJECT.
546     */
547    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
548
549    public static final String PLATFORM_PACKAGE_NAME = "android";
550
551    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
552
553    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
554            DEFAULT_CONTAINER_PACKAGE,
555            "com.android.defcontainer.DefaultContainerService");
556
557    private static final String KILL_APP_REASON_GIDS_CHANGED =
558            "permission grant or revoke changed gids";
559
560    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
561            "permissions revoked";
562
563    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
564
565    private static final String PACKAGE_SCHEME = "package";
566
567    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
568
569    private static final String PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB = "pm.dexopt.priv-apps-oob";
570
571    /** Canonical intent used to identify what counts as a "web browser" app */
572    private static final Intent sBrowserIntent;
573    static {
574        sBrowserIntent = new Intent();
575        sBrowserIntent.setAction(Intent.ACTION_VIEW);
576        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
577        sBrowserIntent.setData(Uri.parse("http:"));
578    }
579
580    /**
581     * The set of all protected actions [i.e. those actions for which a high priority
582     * intent filter is disallowed].
583     */
584    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
585    static {
586        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
587        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
588        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
589        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
590    }
591
592    // Compilation reasons.
593    public static final int REASON_FIRST_BOOT = 0;
594    public static final int REASON_BOOT = 1;
595    public static final int REASON_INSTALL = 2;
596    public static final int REASON_BACKGROUND_DEXOPT = 3;
597    public static final int REASON_AB_OTA = 4;
598    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
599    public static final int REASON_SHARED = 6;
600
601    public static final int REASON_LAST = REASON_SHARED;
602
603    /**
604     * Version number for the package parser cache. Increment this whenever the format or
605     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
606     */
607    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
608
609    /**
610     * Whether the package parser cache is enabled.
611     */
612    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
613
614    /**
615     * Permissions required in order to receive instant application lifecycle broadcasts.
616     */
617    private static final String[] INSTANT_APP_BROADCAST_PERMISSION =
618            new String[] { android.Manifest.permission.ACCESS_INSTANT_APPS };
619
620    final ServiceThread mHandlerThread;
621
622    final PackageHandler mHandler;
623
624    private final ProcessLoggingHandler mProcessLoggingHandler;
625
626    /**
627     * Messages for {@link #mHandler} that need to wait for system ready before
628     * being dispatched.
629     */
630    private ArrayList<Message> mPostSystemReadyMessages;
631
632    final int mSdkVersion = Build.VERSION.SDK_INT;
633
634    final Context mContext;
635    final boolean mFactoryTest;
636    final boolean mOnlyCore;
637    final DisplayMetrics mMetrics;
638    final int mDefParseFlags;
639    final String[] mSeparateProcesses;
640    final boolean mIsUpgrade;
641    final boolean mIsPreNUpgrade;
642    final boolean mIsPreNMR1Upgrade;
643
644    // Have we told the Activity Manager to whitelist the default container service by uid yet?
645    @GuardedBy("mPackages")
646    boolean mDefaultContainerWhitelisted = false;
647
648    @GuardedBy("mPackages")
649    private boolean mDexOptDialogShown;
650
651    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
652    // LOCK HELD.  Can be called with mInstallLock held.
653    @GuardedBy("mInstallLock")
654    final Installer mInstaller;
655
656    /** Directory where installed applications are stored */
657    private static final File sAppInstallDir =
658            new File(Environment.getDataDirectory(), "app");
659    /** Directory where installed application's 32-bit native libraries are copied. */
660    private static final File sAppLib32InstallDir =
661            new File(Environment.getDataDirectory(), "app-lib");
662    /** Directory where code and non-resource assets of forward-locked applications are stored */
663    private static final File sDrmAppPrivateInstallDir =
664            new File(Environment.getDataDirectory(), "app-private");
665
666    // ----------------------------------------------------------------
667
668    // Lock for state used when installing and doing other long running
669    // operations.  Methods that must be called with this lock held have
670    // the suffix "LI".
671    final Object mInstallLock = new Object();
672
673    // ----------------------------------------------------------------
674
675    // Keys are String (package name), values are Package.  This also serves
676    // as the lock for the global state.  Methods that must be called with
677    // this lock held have the prefix "LP".
678    @GuardedBy("mPackages")
679    final ArrayMap<String, PackageParser.Package> mPackages =
680            new ArrayMap<String, PackageParser.Package>();
681
682    final ArrayMap<String, Set<String>> mKnownCodebase =
683            new ArrayMap<String, Set<String>>();
684
685    // Keys are isolated uids and values are the uid of the application
686    // that created the isolated proccess.
687    @GuardedBy("mPackages")
688    final SparseIntArray mIsolatedOwners = new SparseIntArray();
689
690    /**
691     * Tracks new system packages [received in an OTA] that we expect to
692     * find updated user-installed versions. Keys are package name, values
693     * are package location.
694     */
695    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
696    /**
697     * Tracks high priority intent filters for protected actions. During boot, certain
698     * filter actions are protected and should never be allowed to have a high priority
699     * intent filter for them. However, there is one, and only one exception -- the
700     * setup wizard. It must be able to define a high priority intent filter for these
701     * actions to ensure there are no escapes from the wizard. We need to delay processing
702     * of these during boot as we need to look at all of the system packages in order
703     * to know which component is the setup wizard.
704     */
705    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
706    /**
707     * Whether or not processing protected filters should be deferred.
708     */
709    private boolean mDeferProtectedFilters = true;
710
711    /**
712     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
713     */
714    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
715    /**
716     * Whether or not system app permissions should be promoted from install to runtime.
717     */
718    boolean mPromoteSystemApps;
719
720    @GuardedBy("mPackages")
721    final Settings mSettings;
722
723    /**
724     * Set of package names that are currently "frozen", which means active
725     * surgery is being done on the code/data for that package. The platform
726     * will refuse to launch frozen packages to avoid race conditions.
727     *
728     * @see PackageFreezer
729     */
730    @GuardedBy("mPackages")
731    final ArraySet<String> mFrozenPackages = new ArraySet<>();
732
733    final ProtectedPackages mProtectedPackages;
734
735    @GuardedBy("mLoadedVolumes")
736    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
737
738    boolean mFirstBoot;
739
740    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
741
742    @GuardedBy("mAvailableFeatures")
743    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
744
745    private final InstantAppRegistry mInstantAppRegistry;
746
747    @GuardedBy("mPackages")
748    int mChangedPackagesSequenceNumber;
749    /**
750     * List of changed [installed, removed or updated] packages.
751     * mapping from user id -> sequence number -> package name
752     */
753    @GuardedBy("mPackages")
754    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
755    /**
756     * The sequence number of the last change to a package.
757     * mapping from user id -> package name -> sequence number
758     */
759    @GuardedBy("mPackages")
760    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
761
762    @GuardedBy("mPackages")
763    final private ArraySet<PackageListObserver> mPackageListObservers = new ArraySet<>();
764
765    class PackageParserCallback implements PackageParser.Callback {
766        @Override public final boolean hasFeature(String feature) {
767            return PackageManagerService.this.hasSystemFeature(feature, 0);
768        }
769
770        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
771                Collection<PackageParser.Package> allPackages, String targetPackageName) {
772            List<PackageParser.Package> overlayPackages = null;
773            for (PackageParser.Package p : allPackages) {
774                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
775                    if (overlayPackages == null) {
776                        overlayPackages = new ArrayList<PackageParser.Package>();
777                    }
778                    overlayPackages.add(p);
779                }
780            }
781            if (overlayPackages != null) {
782                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
783                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
784                        return p1.mOverlayPriority - p2.mOverlayPriority;
785                    }
786                };
787                Collections.sort(overlayPackages, cmp);
788            }
789            return overlayPackages;
790        }
791
792        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
793                String targetPackageName, String targetPath) {
794            if ("android".equals(targetPackageName)) {
795                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
796                // native AssetManager.
797                return null;
798            }
799            List<PackageParser.Package> overlayPackages =
800                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
801            if (overlayPackages == null || overlayPackages.isEmpty()) {
802                return null;
803            }
804            List<String> overlayPathList = null;
805            for (PackageParser.Package overlayPackage : overlayPackages) {
806                if (targetPath == null) {
807                    if (overlayPathList == null) {
808                        overlayPathList = new ArrayList<String>();
809                    }
810                    overlayPathList.add(overlayPackage.baseCodePath);
811                    continue;
812                }
813
814                try {
815                    // Creates idmaps for system to parse correctly the Android manifest of the
816                    // target package.
817                    //
818                    // OverlayManagerService will update each of them with a correct gid from its
819                    // target package app id.
820                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
821                            UserHandle.getSharedAppGid(
822                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
823                    if (overlayPathList == null) {
824                        overlayPathList = new ArrayList<String>();
825                    }
826                    overlayPathList.add(overlayPackage.baseCodePath);
827                } catch (InstallerException e) {
828                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
829                            overlayPackage.baseCodePath);
830                }
831            }
832            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
833        }
834
835        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
836            synchronized (mPackages) {
837                return getStaticOverlayPathsLocked(
838                        mPackages.values(), targetPackageName, targetPath);
839            }
840        }
841
842        @Override public final String[] getOverlayApks(String targetPackageName) {
843            return getStaticOverlayPaths(targetPackageName, null);
844        }
845
846        @Override public final String[] getOverlayPaths(String targetPackageName,
847                String targetPath) {
848            return getStaticOverlayPaths(targetPackageName, targetPath);
849        }
850    }
851
852    class ParallelPackageParserCallback extends PackageParserCallback {
853        List<PackageParser.Package> mOverlayPackages = null;
854
855        void findStaticOverlayPackages() {
856            synchronized (mPackages) {
857                for (PackageParser.Package p : mPackages.values()) {
858                    if (p.mIsStaticOverlay) {
859                        if (mOverlayPackages == null) {
860                            mOverlayPackages = new ArrayList<PackageParser.Package>();
861                        }
862                        mOverlayPackages.add(p);
863                    }
864                }
865            }
866        }
867
868        @Override
869        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
870            // We can trust mOverlayPackages without holding mPackages because package uninstall
871            // can't happen while running parallel parsing.
872            // Moreover holding mPackages on each parsing thread causes dead-lock.
873            return mOverlayPackages == null ? null :
874                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
875        }
876    }
877
878    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
879    final ParallelPackageParserCallback mParallelPackageParserCallback =
880            new ParallelPackageParserCallback();
881
882    public static final class SharedLibraryEntry {
883        public final @Nullable String path;
884        public final @Nullable String apk;
885        public final @NonNull SharedLibraryInfo info;
886
887        SharedLibraryEntry(String _path, String _apk, String name, long version, int type,
888                String declaringPackageName, long declaringPackageVersionCode) {
889            path = _path;
890            apk = _apk;
891            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
892                    declaringPackageName, declaringPackageVersionCode), null);
893        }
894    }
895
896    // Currently known shared libraries.
897    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
898    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
899            new ArrayMap<>();
900
901    // All available activities, for your resolving pleasure.
902    final ActivityIntentResolver mActivities =
903            new ActivityIntentResolver();
904
905    // All available receivers, for your resolving pleasure.
906    final ActivityIntentResolver mReceivers =
907            new ActivityIntentResolver();
908
909    // All available services, for your resolving pleasure.
910    final ServiceIntentResolver mServices = new ServiceIntentResolver();
911
912    // All available providers, for your resolving pleasure.
913    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
914
915    // Mapping from provider base names (first directory in content URI codePath)
916    // to the provider information.
917    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
918            new ArrayMap<String, PackageParser.Provider>();
919
920    // Mapping from instrumentation class names to info about them.
921    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
922            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
923
924    // Packages whose data we have transfered into another package, thus
925    // should no longer exist.
926    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
927
928    // Broadcast actions that are only available to the system.
929    @GuardedBy("mProtectedBroadcasts")
930    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
931
932    /** List of packages waiting for verification. */
933    final SparseArray<PackageVerificationState> mPendingVerification
934            = new SparseArray<PackageVerificationState>();
935
936    final PackageInstallerService mInstallerService;
937
938    final ArtManagerService mArtManagerService;
939
940    private final PackageDexOptimizer mPackageDexOptimizer;
941    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
942    // is used by other apps).
943    private final DexManager mDexManager;
944
945    private AtomicInteger mNextMoveId = new AtomicInteger();
946    private final MoveCallbacks mMoveCallbacks;
947
948    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
949
950    // Cache of users who need badging.
951    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
952
953    /** Token for keys in mPendingVerification. */
954    private int mPendingVerificationToken = 0;
955
956    volatile boolean mSystemReady;
957    volatile boolean mSafeMode;
958    volatile boolean mHasSystemUidErrors;
959    private volatile boolean mEphemeralAppsDisabled;
960
961    ApplicationInfo mAndroidApplication;
962    final ActivityInfo mResolveActivity = new ActivityInfo();
963    final ResolveInfo mResolveInfo = new ResolveInfo();
964    ComponentName mResolveComponentName;
965    PackageParser.Package mPlatformPackage;
966    ComponentName mCustomResolverComponentName;
967
968    boolean mResolverReplaced = false;
969
970    private final @Nullable ComponentName mIntentFilterVerifierComponent;
971    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
972
973    private int mIntentFilterVerificationToken = 0;
974
975    /** The service connection to the ephemeral resolver */
976    final EphemeralResolverConnection mInstantAppResolverConnection;
977    /** Component used to show resolver settings for Instant Apps */
978    final ComponentName mInstantAppResolverSettingsComponent;
979
980    /** Activity used to install instant applications */
981    ActivityInfo mInstantAppInstallerActivity;
982    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
983
984    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
985            = new SparseArray<IntentFilterVerificationState>();
986
987    // TODO remove this and go through mPermissonManager directly
988    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
989    private final PermissionManagerInternal mPermissionManager;
990
991    // List of packages names to keep cached, even if they are uninstalled for all users
992    private List<String> mKeepUninstalledPackages;
993
994    private UserManagerInternal mUserManagerInternal;
995
996    private DeviceIdleController.LocalService mDeviceIdleController;
997
998    private File mCacheDir;
999
1000    private Future<?> mPrepareAppDataFuture;
1001
1002    private static class IFVerificationParams {
1003        PackageParser.Package pkg;
1004        boolean replacing;
1005        int userId;
1006        int verifierUid;
1007
1008        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1009                int _userId, int _verifierUid) {
1010            pkg = _pkg;
1011            replacing = _replacing;
1012            userId = _userId;
1013            replacing = _replacing;
1014            verifierUid = _verifierUid;
1015        }
1016    }
1017
1018    private interface IntentFilterVerifier<T extends IntentFilter> {
1019        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1020                                               T filter, String packageName);
1021        void startVerifications(int userId);
1022        void receiveVerificationResponse(int verificationId);
1023    }
1024
1025    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1026        private Context mContext;
1027        private ComponentName mIntentFilterVerifierComponent;
1028        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1029
1030        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1031            mContext = context;
1032            mIntentFilterVerifierComponent = verifierComponent;
1033        }
1034
1035        private String getDefaultScheme() {
1036            return IntentFilter.SCHEME_HTTPS;
1037        }
1038
1039        @Override
1040        public void startVerifications(int userId) {
1041            // Launch verifications requests
1042            int count = mCurrentIntentFilterVerifications.size();
1043            for (int n=0; n<count; n++) {
1044                int verificationId = mCurrentIntentFilterVerifications.get(n);
1045                final IntentFilterVerificationState ivs =
1046                        mIntentFilterVerificationStates.get(verificationId);
1047
1048                String packageName = ivs.getPackageName();
1049
1050                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1051                final int filterCount = filters.size();
1052                ArraySet<String> domainsSet = new ArraySet<>();
1053                for (int m=0; m<filterCount; m++) {
1054                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1055                    domainsSet.addAll(filter.getHostsList());
1056                }
1057                synchronized (mPackages) {
1058                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1059                            packageName, domainsSet) != null) {
1060                        scheduleWriteSettingsLocked();
1061                    }
1062                }
1063                sendVerificationRequest(verificationId, ivs);
1064            }
1065            mCurrentIntentFilterVerifications.clear();
1066        }
1067
1068        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1069            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1070            verificationIntent.putExtra(
1071                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1072                    verificationId);
1073            verificationIntent.putExtra(
1074                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1075                    getDefaultScheme());
1076            verificationIntent.putExtra(
1077                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1078                    ivs.getHostsString());
1079            verificationIntent.putExtra(
1080                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1081                    ivs.getPackageName());
1082            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1083            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1084
1085            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1086            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1087                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1088                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1089
1090            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1091            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1092                    "Sending IntentFilter verification broadcast");
1093        }
1094
1095        public void receiveVerificationResponse(int verificationId) {
1096            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1097
1098            final boolean verified = ivs.isVerified();
1099
1100            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1101            final int count = filters.size();
1102            if (DEBUG_DOMAIN_VERIFICATION) {
1103                Slog.i(TAG, "Received verification response " + verificationId
1104                        + " for " + count + " filters, verified=" + verified);
1105            }
1106            for (int n=0; n<count; n++) {
1107                PackageParser.ActivityIntentInfo filter = filters.get(n);
1108                filter.setVerified(verified);
1109
1110                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1111                        + " verified with result:" + verified + " and hosts:"
1112                        + ivs.getHostsString());
1113            }
1114
1115            mIntentFilterVerificationStates.remove(verificationId);
1116
1117            final String packageName = ivs.getPackageName();
1118            IntentFilterVerificationInfo ivi = null;
1119
1120            synchronized (mPackages) {
1121                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1122            }
1123            if (ivi == null) {
1124                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1125                        + verificationId + " packageName:" + packageName);
1126                return;
1127            }
1128            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1129                    "Updating IntentFilterVerificationInfo for package " + packageName
1130                            +" verificationId:" + verificationId);
1131
1132            synchronized (mPackages) {
1133                if (verified) {
1134                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1135                } else {
1136                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1137                }
1138                scheduleWriteSettingsLocked();
1139
1140                final int userId = ivs.getUserId();
1141                if (userId != UserHandle.USER_ALL) {
1142                    final int userStatus =
1143                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1144
1145                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1146                    boolean needUpdate = false;
1147
1148                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1149                    // already been set by the User thru the Disambiguation dialog
1150                    switch (userStatus) {
1151                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1152                            if (verified) {
1153                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1154                            } else {
1155                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1156                            }
1157                            needUpdate = true;
1158                            break;
1159
1160                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1161                            if (verified) {
1162                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1163                                needUpdate = true;
1164                            }
1165                            break;
1166
1167                        default:
1168                            // Nothing to do
1169                    }
1170
1171                    if (needUpdate) {
1172                        mSettings.updateIntentFilterVerificationStatusLPw(
1173                                packageName, updatedStatus, userId);
1174                        scheduleWritePackageRestrictionsLocked(userId);
1175                    }
1176                }
1177            }
1178        }
1179
1180        @Override
1181        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1182                    ActivityIntentInfo filter, String packageName) {
1183            if (!hasValidDomains(filter)) {
1184                return false;
1185            }
1186            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1187            if (ivs == null) {
1188                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1189                        packageName);
1190            }
1191            if (DEBUG_DOMAIN_VERIFICATION) {
1192                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1193            }
1194            ivs.addFilter(filter);
1195            return true;
1196        }
1197
1198        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1199                int userId, int verificationId, String packageName) {
1200            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1201                    verifierUid, userId, packageName);
1202            ivs.setPendingState();
1203            synchronized (mPackages) {
1204                mIntentFilterVerificationStates.append(verificationId, ivs);
1205                mCurrentIntentFilterVerifications.add(verificationId);
1206            }
1207            return ivs;
1208        }
1209    }
1210
1211    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1212        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1213                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1214                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1215    }
1216
1217    // Set of pending broadcasts for aggregating enable/disable of components.
1218    static class PendingPackageBroadcasts {
1219        // for each user id, a map of <package name -> components within that package>
1220        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1221
1222        public PendingPackageBroadcasts() {
1223            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1224        }
1225
1226        public ArrayList<String> get(int userId, String packageName) {
1227            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1228            return packages.get(packageName);
1229        }
1230
1231        public void put(int userId, String packageName, ArrayList<String> components) {
1232            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1233            packages.put(packageName, components);
1234        }
1235
1236        public void remove(int userId, String packageName) {
1237            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1238            if (packages != null) {
1239                packages.remove(packageName);
1240            }
1241        }
1242
1243        public void remove(int userId) {
1244            mUidMap.remove(userId);
1245        }
1246
1247        public int userIdCount() {
1248            return mUidMap.size();
1249        }
1250
1251        public int userIdAt(int n) {
1252            return mUidMap.keyAt(n);
1253        }
1254
1255        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1256            return mUidMap.get(userId);
1257        }
1258
1259        public int size() {
1260            // total number of pending broadcast entries across all userIds
1261            int num = 0;
1262            for (int i = 0; i< mUidMap.size(); i++) {
1263                num += mUidMap.valueAt(i).size();
1264            }
1265            return num;
1266        }
1267
1268        public void clear() {
1269            mUidMap.clear();
1270        }
1271
1272        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1273            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1274            if (map == null) {
1275                map = new ArrayMap<String, ArrayList<String>>();
1276                mUidMap.put(userId, map);
1277            }
1278            return map;
1279        }
1280    }
1281    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1282
1283    // Service Connection to remote media container service to copy
1284    // package uri's from external media onto secure containers
1285    // or internal storage.
1286    private IMediaContainerService mContainerService = null;
1287
1288    static final int SEND_PENDING_BROADCAST = 1;
1289    static final int MCS_BOUND = 3;
1290    static final int END_COPY = 4;
1291    static final int INIT_COPY = 5;
1292    static final int MCS_UNBIND = 6;
1293    static final int START_CLEANING_PACKAGE = 7;
1294    static final int FIND_INSTALL_LOC = 8;
1295    static final int POST_INSTALL = 9;
1296    static final int MCS_RECONNECT = 10;
1297    static final int MCS_GIVE_UP = 11;
1298    static final int WRITE_SETTINGS = 13;
1299    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1300    static final int PACKAGE_VERIFIED = 15;
1301    static final int CHECK_PENDING_VERIFICATION = 16;
1302    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1303    static final int INTENT_FILTER_VERIFIED = 18;
1304    static final int WRITE_PACKAGE_LIST = 19;
1305    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1306
1307    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1308
1309    // Delay time in millisecs
1310    static final int BROADCAST_DELAY = 10 * 1000;
1311
1312    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1313            2 * 60 * 60 * 1000L; /* two hours */
1314
1315    static UserManagerService sUserManager;
1316
1317    // Stores a list of users whose package restrictions file needs to be updated
1318    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1319
1320    final private DefaultContainerConnection mDefContainerConn =
1321            new DefaultContainerConnection();
1322    class DefaultContainerConnection implements ServiceConnection {
1323        public void onServiceConnected(ComponentName name, IBinder service) {
1324            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1325            final IMediaContainerService imcs = IMediaContainerService.Stub
1326                    .asInterface(Binder.allowBlocking(service));
1327            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1328        }
1329
1330        public void onServiceDisconnected(ComponentName name) {
1331            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1332        }
1333    }
1334
1335    // Recordkeeping of restore-after-install operations that are currently in flight
1336    // between the Package Manager and the Backup Manager
1337    static class PostInstallData {
1338        public InstallArgs args;
1339        public PackageInstalledInfo res;
1340
1341        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1342            args = _a;
1343            res = _r;
1344        }
1345    }
1346
1347    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1348    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1349
1350    // XML tags for backup/restore of various bits of state
1351    private static final String TAG_PREFERRED_BACKUP = "pa";
1352    private static final String TAG_DEFAULT_APPS = "da";
1353    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1354
1355    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1356    private static final String TAG_ALL_GRANTS = "rt-grants";
1357    private static final String TAG_GRANT = "grant";
1358    private static final String ATTR_PACKAGE_NAME = "pkg";
1359
1360    private static final String TAG_PERMISSION = "perm";
1361    private static final String ATTR_PERMISSION_NAME = "name";
1362    private static final String ATTR_IS_GRANTED = "g";
1363    private static final String ATTR_USER_SET = "set";
1364    private static final String ATTR_USER_FIXED = "fixed";
1365    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1366
1367    // System/policy permission grants are not backed up
1368    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1369            FLAG_PERMISSION_POLICY_FIXED
1370            | FLAG_PERMISSION_SYSTEM_FIXED
1371            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1372
1373    // And we back up these user-adjusted states
1374    private static final int USER_RUNTIME_GRANT_MASK =
1375            FLAG_PERMISSION_USER_SET
1376            | FLAG_PERMISSION_USER_FIXED
1377            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1378
1379    final @Nullable String mRequiredVerifierPackage;
1380    final @NonNull String mRequiredInstallerPackage;
1381    final @NonNull String mRequiredUninstallerPackage;
1382    final @Nullable String mSetupWizardPackage;
1383    final @Nullable String mStorageManagerPackage;
1384    final @NonNull String mServicesSystemSharedLibraryPackageName;
1385    final @NonNull String mSharedSystemSharedLibraryPackageName;
1386
1387    private final PackageUsage mPackageUsage = new PackageUsage();
1388    private final CompilerStats mCompilerStats = new CompilerStats();
1389
1390    class PackageHandler extends Handler {
1391        private boolean mBound = false;
1392        final ArrayList<HandlerParams> mPendingInstalls =
1393            new ArrayList<HandlerParams>();
1394
1395        private boolean connectToService() {
1396            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1397                    " DefaultContainerService");
1398            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1399            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1400            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1401                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1402                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1403                mBound = true;
1404                return true;
1405            }
1406            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1407            return false;
1408        }
1409
1410        private void disconnectService() {
1411            mContainerService = null;
1412            mBound = false;
1413            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1414            mContext.unbindService(mDefContainerConn);
1415            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1416        }
1417
1418        PackageHandler(Looper looper) {
1419            super(looper);
1420        }
1421
1422        public void handleMessage(Message msg) {
1423            try {
1424                doHandleMessage(msg);
1425            } finally {
1426                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1427            }
1428        }
1429
1430        void doHandleMessage(Message msg) {
1431            switch (msg.what) {
1432                case INIT_COPY: {
1433                    HandlerParams params = (HandlerParams) msg.obj;
1434                    int idx = mPendingInstalls.size();
1435                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1436                    // If a bind was already initiated we dont really
1437                    // need to do anything. The pending install
1438                    // will be processed later on.
1439                    if (!mBound) {
1440                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1441                                System.identityHashCode(mHandler));
1442                        // If this is the only one pending we might
1443                        // have to bind to the service again.
1444                        if (!connectToService()) {
1445                            Slog.e(TAG, "Failed to bind to media container service");
1446                            params.serviceError();
1447                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1448                                    System.identityHashCode(mHandler));
1449                            if (params.traceMethod != null) {
1450                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1451                                        params.traceCookie);
1452                            }
1453                            return;
1454                        } else {
1455                            // Once we bind to the service, the first
1456                            // pending request will be processed.
1457                            mPendingInstalls.add(idx, params);
1458                        }
1459                    } else {
1460                        mPendingInstalls.add(idx, params);
1461                        // Already bound to the service. Just make
1462                        // sure we trigger off processing the first request.
1463                        if (idx == 0) {
1464                            mHandler.sendEmptyMessage(MCS_BOUND);
1465                        }
1466                    }
1467                    break;
1468                }
1469                case MCS_BOUND: {
1470                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1471                    if (msg.obj != null) {
1472                        mContainerService = (IMediaContainerService) msg.obj;
1473                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1474                                System.identityHashCode(mHandler));
1475                    }
1476                    if (mContainerService == null) {
1477                        if (!mBound) {
1478                            // Something seriously wrong since we are not bound and we are not
1479                            // waiting for connection. Bail out.
1480                            Slog.e(TAG, "Cannot bind to media container service");
1481                            for (HandlerParams params : mPendingInstalls) {
1482                                // Indicate service bind error
1483                                params.serviceError();
1484                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1485                                        System.identityHashCode(params));
1486                                if (params.traceMethod != null) {
1487                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1488                                            params.traceMethod, params.traceCookie);
1489                                }
1490                                return;
1491                            }
1492                            mPendingInstalls.clear();
1493                        } else {
1494                            Slog.w(TAG, "Waiting to connect to media container service");
1495                        }
1496                    } else if (mPendingInstalls.size() > 0) {
1497                        HandlerParams params = mPendingInstalls.get(0);
1498                        if (params != null) {
1499                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1500                                    System.identityHashCode(params));
1501                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1502                            if (params.startCopy()) {
1503                                // We are done...  look for more work or to
1504                                // go idle.
1505                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1506                                        "Checking for more work or unbind...");
1507                                // Delete pending install
1508                                if (mPendingInstalls.size() > 0) {
1509                                    mPendingInstalls.remove(0);
1510                                }
1511                                if (mPendingInstalls.size() == 0) {
1512                                    if (mBound) {
1513                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1514                                                "Posting delayed MCS_UNBIND");
1515                                        removeMessages(MCS_UNBIND);
1516                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1517                                        // Unbind after a little delay, to avoid
1518                                        // continual thrashing.
1519                                        sendMessageDelayed(ubmsg, 10000);
1520                                    }
1521                                } else {
1522                                    // There are more pending requests in queue.
1523                                    // Just post MCS_BOUND message to trigger processing
1524                                    // of next pending install.
1525                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1526                                            "Posting MCS_BOUND for next work");
1527                                    mHandler.sendEmptyMessage(MCS_BOUND);
1528                                }
1529                            }
1530                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1531                        }
1532                    } else {
1533                        // Should never happen ideally.
1534                        Slog.w(TAG, "Empty queue");
1535                    }
1536                    break;
1537                }
1538                case MCS_RECONNECT: {
1539                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1540                    if (mPendingInstalls.size() > 0) {
1541                        if (mBound) {
1542                            disconnectService();
1543                        }
1544                        if (!connectToService()) {
1545                            Slog.e(TAG, "Failed to bind to media container service");
1546                            for (HandlerParams params : mPendingInstalls) {
1547                                // Indicate service bind error
1548                                params.serviceError();
1549                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1550                                        System.identityHashCode(params));
1551                            }
1552                            mPendingInstalls.clear();
1553                        }
1554                    }
1555                    break;
1556                }
1557                case MCS_UNBIND: {
1558                    // If there is no actual work left, then time to unbind.
1559                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1560
1561                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1562                        if (mBound) {
1563                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1564
1565                            disconnectService();
1566                        }
1567                    } else if (mPendingInstalls.size() > 0) {
1568                        // There are more pending requests in queue.
1569                        // Just post MCS_BOUND message to trigger processing
1570                        // of next pending install.
1571                        mHandler.sendEmptyMessage(MCS_BOUND);
1572                    }
1573
1574                    break;
1575                }
1576                case MCS_GIVE_UP: {
1577                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1578                    HandlerParams params = mPendingInstalls.remove(0);
1579                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1580                            System.identityHashCode(params));
1581                    break;
1582                }
1583                case SEND_PENDING_BROADCAST: {
1584                    String packages[];
1585                    ArrayList<String> components[];
1586                    int size = 0;
1587                    int uids[];
1588                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1589                    synchronized (mPackages) {
1590                        if (mPendingBroadcasts == null) {
1591                            return;
1592                        }
1593                        size = mPendingBroadcasts.size();
1594                        if (size <= 0) {
1595                            // Nothing to be done. Just return
1596                            return;
1597                        }
1598                        packages = new String[size];
1599                        components = new ArrayList[size];
1600                        uids = new int[size];
1601                        int i = 0;  // filling out the above arrays
1602
1603                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1604                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1605                            Iterator<Map.Entry<String, ArrayList<String>>> it
1606                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1607                                            .entrySet().iterator();
1608                            while (it.hasNext() && i < size) {
1609                                Map.Entry<String, ArrayList<String>> ent = it.next();
1610                                packages[i] = ent.getKey();
1611                                components[i] = ent.getValue();
1612                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1613                                uids[i] = (ps != null)
1614                                        ? UserHandle.getUid(packageUserId, ps.appId)
1615                                        : -1;
1616                                i++;
1617                            }
1618                        }
1619                        size = i;
1620                        mPendingBroadcasts.clear();
1621                    }
1622                    // Send broadcasts
1623                    for (int i = 0; i < size; i++) {
1624                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1625                    }
1626                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1627                    break;
1628                }
1629                case START_CLEANING_PACKAGE: {
1630                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1631                    final String packageName = (String)msg.obj;
1632                    final int userId = msg.arg1;
1633                    final boolean andCode = msg.arg2 != 0;
1634                    synchronized (mPackages) {
1635                        if (userId == UserHandle.USER_ALL) {
1636                            int[] users = sUserManager.getUserIds();
1637                            for (int user : users) {
1638                                mSettings.addPackageToCleanLPw(
1639                                        new PackageCleanItem(user, packageName, andCode));
1640                            }
1641                        } else {
1642                            mSettings.addPackageToCleanLPw(
1643                                    new PackageCleanItem(userId, packageName, andCode));
1644                        }
1645                    }
1646                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1647                    startCleaningPackages();
1648                } break;
1649                case POST_INSTALL: {
1650                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1651
1652                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1653                    final boolean didRestore = (msg.arg2 != 0);
1654                    mRunningInstalls.delete(msg.arg1);
1655
1656                    if (data != null) {
1657                        InstallArgs args = data.args;
1658                        PackageInstalledInfo parentRes = data.res;
1659
1660                        final boolean grantPermissions = (args.installFlags
1661                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1662                        final boolean killApp = (args.installFlags
1663                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1664                        final boolean virtualPreload = ((args.installFlags
1665                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1666                        final String[] grantedPermissions = args.installGrantPermissions;
1667
1668                        // Handle the parent package
1669                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1670                                virtualPreload, grantedPermissions, didRestore,
1671                                args.installerPackageName, args.observer);
1672
1673                        // Handle the child packages
1674                        final int childCount = (parentRes.addedChildPackages != null)
1675                                ? parentRes.addedChildPackages.size() : 0;
1676                        for (int i = 0; i < childCount; i++) {
1677                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1678                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1679                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1680                                    args.installerPackageName, args.observer);
1681                        }
1682
1683                        // Log tracing if needed
1684                        if (args.traceMethod != null) {
1685                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1686                                    args.traceCookie);
1687                        }
1688                    } else {
1689                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1690                    }
1691
1692                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1693                } break;
1694                case WRITE_SETTINGS: {
1695                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1696                    synchronized (mPackages) {
1697                        removeMessages(WRITE_SETTINGS);
1698                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1699                        mSettings.writeLPr();
1700                        mDirtyUsers.clear();
1701                    }
1702                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1703                } break;
1704                case WRITE_PACKAGE_RESTRICTIONS: {
1705                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1706                    synchronized (mPackages) {
1707                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1708                        for (int userId : mDirtyUsers) {
1709                            mSettings.writePackageRestrictionsLPr(userId);
1710                        }
1711                        mDirtyUsers.clear();
1712                    }
1713                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1714                } break;
1715                case WRITE_PACKAGE_LIST: {
1716                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1717                    synchronized (mPackages) {
1718                        removeMessages(WRITE_PACKAGE_LIST);
1719                        mSettings.writePackageListLPr(msg.arg1);
1720                    }
1721                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1722                } break;
1723                case CHECK_PENDING_VERIFICATION: {
1724                    final int verificationId = msg.arg1;
1725                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1726
1727                    if ((state != null) && !state.timeoutExtended()) {
1728                        final InstallArgs args = state.getInstallArgs();
1729                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1730
1731                        Slog.i(TAG, "Verification timed out for " + originUri);
1732                        mPendingVerification.remove(verificationId);
1733
1734                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1735
1736                        final UserHandle user = args.getUser();
1737                        if (getDefaultVerificationResponse(user)
1738                                == PackageManager.VERIFICATION_ALLOW) {
1739                            Slog.i(TAG, "Continuing with installation of " + originUri);
1740                            state.setVerifierResponse(Binder.getCallingUid(),
1741                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1742                            broadcastPackageVerified(verificationId, originUri,
1743                                    PackageManager.VERIFICATION_ALLOW, user);
1744                            try {
1745                                ret = args.copyApk(mContainerService, true);
1746                            } catch (RemoteException e) {
1747                                Slog.e(TAG, "Could not contact the ContainerService");
1748                            }
1749                        } else {
1750                            broadcastPackageVerified(verificationId, originUri,
1751                                    PackageManager.VERIFICATION_REJECT, user);
1752                        }
1753
1754                        Trace.asyncTraceEnd(
1755                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1756
1757                        processPendingInstall(args, ret);
1758                        mHandler.sendEmptyMessage(MCS_UNBIND);
1759                    }
1760                    break;
1761                }
1762                case PACKAGE_VERIFIED: {
1763                    final int verificationId = msg.arg1;
1764
1765                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1766                    if (state == null) {
1767                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1768                        break;
1769                    }
1770
1771                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1772
1773                    state.setVerifierResponse(response.callerUid, response.code);
1774
1775                    if (state.isVerificationComplete()) {
1776                        mPendingVerification.remove(verificationId);
1777
1778                        final InstallArgs args = state.getInstallArgs();
1779                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1780
1781                        int ret;
1782                        if (state.isInstallAllowed()) {
1783                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1784                            broadcastPackageVerified(verificationId, originUri,
1785                                    response.code, state.getInstallArgs().getUser());
1786                            try {
1787                                ret = args.copyApk(mContainerService, true);
1788                            } catch (RemoteException e) {
1789                                Slog.e(TAG, "Could not contact the ContainerService");
1790                            }
1791                        } else {
1792                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1793                        }
1794
1795                        Trace.asyncTraceEnd(
1796                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1797
1798                        processPendingInstall(args, ret);
1799                        mHandler.sendEmptyMessage(MCS_UNBIND);
1800                    }
1801
1802                    break;
1803                }
1804                case START_INTENT_FILTER_VERIFICATIONS: {
1805                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1806                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1807                            params.replacing, params.pkg);
1808                    break;
1809                }
1810                case INTENT_FILTER_VERIFIED: {
1811                    final int verificationId = msg.arg1;
1812
1813                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1814                            verificationId);
1815                    if (state == null) {
1816                        Slog.w(TAG, "Invalid IntentFilter verification token "
1817                                + verificationId + " received");
1818                        break;
1819                    }
1820
1821                    final int userId = state.getUserId();
1822
1823                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1824                            "Processing IntentFilter verification with token:"
1825                            + verificationId + " and userId:" + userId);
1826
1827                    final IntentFilterVerificationResponse response =
1828                            (IntentFilterVerificationResponse) msg.obj;
1829
1830                    state.setVerifierResponse(response.callerUid, response.code);
1831
1832                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1833                            "IntentFilter verification with token:" + verificationId
1834                            + " and userId:" + userId
1835                            + " is settings verifier response with response code:"
1836                            + response.code);
1837
1838                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1839                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1840                                + response.getFailedDomainsString());
1841                    }
1842
1843                    if (state.isVerificationComplete()) {
1844                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1845                    } else {
1846                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1847                                "IntentFilter verification with token:" + verificationId
1848                                + " was not said to be complete");
1849                    }
1850
1851                    break;
1852                }
1853                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1854                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1855                            mInstantAppResolverConnection,
1856                            (InstantAppRequest) msg.obj,
1857                            mInstantAppInstallerActivity,
1858                            mHandler);
1859                }
1860            }
1861        }
1862    }
1863
1864    private PermissionCallback mPermissionCallback = new PermissionCallback() {
1865        @Override
1866        public void onGidsChanged(int appId, int userId) {
1867            mHandler.post(new Runnable() {
1868                @Override
1869                public void run() {
1870                    killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
1871                }
1872            });
1873        }
1874        @Override
1875        public void onPermissionGranted(int uid, int userId) {
1876            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1877
1878            // Not critical; if this is lost, the application has to request again.
1879            synchronized (mPackages) {
1880                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1881            }
1882        }
1883        @Override
1884        public void onInstallPermissionGranted() {
1885            synchronized (mPackages) {
1886                scheduleWriteSettingsLocked();
1887            }
1888        }
1889        @Override
1890        public void onPermissionRevoked(int uid, int userId) {
1891            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1892
1893            synchronized (mPackages) {
1894                // Critical; after this call the application should never have the permission
1895                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
1896            }
1897
1898            final int appId = UserHandle.getAppId(uid);
1899            killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
1900        }
1901        @Override
1902        public void onInstallPermissionRevoked() {
1903            synchronized (mPackages) {
1904                scheduleWriteSettingsLocked();
1905            }
1906        }
1907        @Override
1908        public void onPermissionUpdated(int[] updatedUserIds, boolean sync) {
1909            synchronized (mPackages) {
1910                for (int userId : updatedUserIds) {
1911                    mSettings.writeRuntimePermissionsForUserLPr(userId, sync);
1912                }
1913            }
1914        }
1915        @Override
1916        public void onInstallPermissionUpdated() {
1917            synchronized (mPackages) {
1918                scheduleWriteSettingsLocked();
1919            }
1920        }
1921        @Override
1922        public void onPermissionRemoved() {
1923            synchronized (mPackages) {
1924                mSettings.writeLPr();
1925            }
1926        }
1927    };
1928
1929    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1930            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1931            boolean launchedForRestore, String installerPackage,
1932            IPackageInstallObserver2 installObserver) {
1933        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1934            // Send the removed broadcasts
1935            if (res.removedInfo != null) {
1936                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1937            }
1938
1939            // Now that we successfully installed the package, grant runtime
1940            // permissions if requested before broadcasting the install. Also
1941            // for legacy apps in permission review mode we clear the permission
1942            // review flag which is used to emulate runtime permissions for
1943            // legacy apps.
1944            if (grantPermissions) {
1945                final int callingUid = Binder.getCallingUid();
1946                mPermissionManager.grantRequestedRuntimePermissions(
1947                        res.pkg, res.newUsers, grantedPermissions, callingUid,
1948                        mPermissionCallback);
1949            }
1950
1951            final boolean update = res.removedInfo != null
1952                    && res.removedInfo.removedPackage != null;
1953            final String installerPackageName =
1954                    res.installerPackageName != null
1955                            ? res.installerPackageName
1956                            : res.removedInfo != null
1957                                    ? res.removedInfo.installerPackageName
1958                                    : null;
1959
1960            // If this is the first time we have child packages for a disabled privileged
1961            // app that had no children, we grant requested runtime permissions to the new
1962            // children if the parent on the system image had them already granted.
1963            if (res.pkg.parentPackage != null) {
1964                final int callingUid = Binder.getCallingUid();
1965                mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage(
1966                        res.pkg, callingUid, mPermissionCallback);
1967            }
1968
1969            synchronized (mPackages) {
1970                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1971            }
1972
1973            final String packageName = res.pkg.applicationInfo.packageName;
1974
1975            // Determine the set of users who are adding this package for
1976            // the first time vs. those who are seeing an update.
1977            int[] firstUserIds = EMPTY_INT_ARRAY;
1978            int[] firstInstantUserIds = EMPTY_INT_ARRAY;
1979            int[] updateUserIds = EMPTY_INT_ARRAY;
1980            int[] instantUserIds = EMPTY_INT_ARRAY;
1981            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1982            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1983            for (int newUser : res.newUsers) {
1984                final boolean isInstantApp = ps.getInstantApp(newUser);
1985                if (allNewUsers) {
1986                    if (isInstantApp) {
1987                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
1988                    } else {
1989                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
1990                    }
1991                    continue;
1992                }
1993                boolean isNew = true;
1994                for (int origUser : res.origUsers) {
1995                    if (origUser == newUser) {
1996                        isNew = false;
1997                        break;
1998                    }
1999                }
2000                if (isNew) {
2001                    if (isInstantApp) {
2002                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2003                    } else {
2004                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2005                    }
2006                } else {
2007                    if (isInstantApp) {
2008                        instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser);
2009                    } else {
2010                        updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser);
2011                    }
2012                }
2013            }
2014
2015            // Send installed broadcasts if the package is not a static shared lib.
2016            if (res.pkg.staticSharedLibName == null) {
2017                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
2018
2019                // Send added for users that see the package for the first time
2020                // sendPackageAddedForNewUsers also deals with system apps
2021                int appId = UserHandle.getAppId(res.uid);
2022                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
2023                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
2024                        virtualPreload /*startReceiver*/, appId, firstUserIds, firstInstantUserIds);
2025
2026                // Send added for users that don't see the package for the first time
2027                Bundle extras = new Bundle(1);
2028                extras.putInt(Intent.EXTRA_UID, res.uid);
2029                if (update) {
2030                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2031                }
2032                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2033                        extras, 0 /*flags*/,
2034                        null /*targetPackage*/, null /*finishedReceiver*/,
2035                        updateUserIds, instantUserIds);
2036                if (installerPackageName != null) {
2037                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2038                            extras, 0 /*flags*/,
2039                            installerPackageName, null /*finishedReceiver*/,
2040                            updateUserIds, instantUserIds);
2041                }
2042
2043                // Send replaced for users that don't see the package for the first time
2044                if (update) {
2045                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2046                            packageName, extras, 0 /*flags*/,
2047                            null /*targetPackage*/, null /*finishedReceiver*/,
2048                            updateUserIds, instantUserIds);
2049                    if (installerPackageName != null) {
2050                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2051                                extras, 0 /*flags*/,
2052                                installerPackageName, null /*finishedReceiver*/,
2053                                updateUserIds, instantUserIds);
2054                    }
2055                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2056                            null /*package*/, null /*extras*/, 0 /*flags*/,
2057                            packageName /*targetPackage*/,
2058                            null /*finishedReceiver*/, updateUserIds, instantUserIds);
2059                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2060                    // First-install and we did a restore, so we're responsible for the
2061                    // first-launch broadcast.
2062                    if (DEBUG_BACKUP) {
2063                        Slog.i(TAG, "Post-restore of " + packageName
2064                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds));
2065                    }
2066                    sendFirstLaunchBroadcast(packageName, installerPackage,
2067                            firstUserIds, firstInstantUserIds);
2068                }
2069
2070                // Send broadcast package appeared if forward locked/external for all users
2071                // treat asec-hosted packages like removable media on upgrade
2072                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2073                    if (DEBUG_INSTALL) {
2074                        Slog.i(TAG, "upgrading pkg " + res.pkg
2075                                + " is ASEC-hosted -> AVAILABLE");
2076                    }
2077                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2078                    ArrayList<String> pkgList = new ArrayList<>(1);
2079                    pkgList.add(packageName);
2080                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2081                }
2082            }
2083
2084            // Work that needs to happen on first install within each user
2085            if (firstUserIds != null && firstUserIds.length > 0) {
2086                synchronized (mPackages) {
2087                    for (int userId : firstUserIds) {
2088                        // If this app is a browser and it's newly-installed for some
2089                        // users, clear any default-browser state in those users. The
2090                        // app's nature doesn't depend on the user, so we can just check
2091                        // its browser nature in any user and generalize.
2092                        if (packageIsBrowser(packageName, userId)) {
2093                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2094                        }
2095
2096                        // We may also need to apply pending (restored) runtime
2097                        // permission grants within these users.
2098                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2099                    }
2100                }
2101            }
2102
2103            if (allNewUsers && !update) {
2104                notifyPackageAdded(packageName);
2105            }
2106
2107            // Log current value of "unknown sources" setting
2108            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2109                    getUnknownSourcesSettings());
2110
2111            // Remove the replaced package's older resources safely now
2112            // We delete after a gc for applications  on sdcard.
2113            if (res.removedInfo != null && res.removedInfo.args != null) {
2114                Runtime.getRuntime().gc();
2115                synchronized (mInstallLock) {
2116                    res.removedInfo.args.doPostDeleteLI(true);
2117                }
2118            } else {
2119                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2120                // and not block here.
2121                VMRuntime.getRuntime().requestConcurrentGC();
2122            }
2123
2124            // Notify DexManager that the package was installed for new users.
2125            // The updated users should already be indexed and the package code paths
2126            // should not change.
2127            // Don't notify the manager for ephemeral apps as they are not expected to
2128            // survive long enough to benefit of background optimizations.
2129            for (int userId : firstUserIds) {
2130                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2131                // There's a race currently where some install events may interleave with an uninstall.
2132                // This can lead to package info being null (b/36642664).
2133                if (info != null) {
2134                    mDexManager.notifyPackageInstalled(info, userId);
2135                }
2136            }
2137        }
2138
2139        // If someone is watching installs - notify them
2140        if (installObserver != null) {
2141            try {
2142                Bundle extras = extrasForInstallResult(res);
2143                installObserver.onPackageInstalled(res.name, res.returnCode,
2144                        res.returnMsg, extras);
2145            } catch (RemoteException e) {
2146                Slog.i(TAG, "Observer no longer exists.");
2147            }
2148        }
2149    }
2150
2151    private StorageEventListener mStorageListener = new StorageEventListener() {
2152        @Override
2153        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2154            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2155                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2156                    final String volumeUuid = vol.getFsUuid();
2157
2158                    // Clean up any users or apps that were removed or recreated
2159                    // while this volume was missing
2160                    sUserManager.reconcileUsers(volumeUuid);
2161                    reconcileApps(volumeUuid);
2162
2163                    // Clean up any install sessions that expired or were
2164                    // cancelled while this volume was missing
2165                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2166
2167                    loadPrivatePackages(vol);
2168
2169                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2170                    unloadPrivatePackages(vol);
2171                }
2172            }
2173        }
2174
2175        @Override
2176        public void onVolumeForgotten(String fsUuid) {
2177            if (TextUtils.isEmpty(fsUuid)) {
2178                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2179                return;
2180            }
2181
2182            // Remove any apps installed on the forgotten volume
2183            synchronized (mPackages) {
2184                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2185                for (PackageSetting ps : packages) {
2186                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2187                    deletePackageVersioned(new VersionedPackage(ps.name,
2188                            PackageManager.VERSION_CODE_HIGHEST),
2189                            new LegacyPackageDeleteObserver(null).getBinder(),
2190                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2191                    // Try very hard to release any references to this package
2192                    // so we don't risk the system server being killed due to
2193                    // open FDs
2194                    AttributeCache.instance().removePackage(ps.name);
2195                }
2196
2197                mSettings.onVolumeForgotten(fsUuid);
2198                mSettings.writeLPr();
2199            }
2200        }
2201    };
2202
2203    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2204        Bundle extras = null;
2205        switch (res.returnCode) {
2206            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2207                extras = new Bundle();
2208                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2209                        res.origPermission);
2210                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2211                        res.origPackage);
2212                break;
2213            }
2214            case PackageManager.INSTALL_SUCCEEDED: {
2215                extras = new Bundle();
2216                extras.putBoolean(Intent.EXTRA_REPLACING,
2217                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2218                break;
2219            }
2220        }
2221        return extras;
2222    }
2223
2224    void scheduleWriteSettingsLocked() {
2225        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2226            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2227        }
2228    }
2229
2230    void scheduleWritePackageListLocked(int userId) {
2231        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2232            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2233            msg.arg1 = userId;
2234            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2235        }
2236    }
2237
2238    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2239        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2240        scheduleWritePackageRestrictionsLocked(userId);
2241    }
2242
2243    void scheduleWritePackageRestrictionsLocked(int userId) {
2244        final int[] userIds = (userId == UserHandle.USER_ALL)
2245                ? sUserManager.getUserIds() : new int[]{userId};
2246        for (int nextUserId : userIds) {
2247            if (!sUserManager.exists(nextUserId)) return;
2248            mDirtyUsers.add(nextUserId);
2249            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2250                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2251            }
2252        }
2253    }
2254
2255    public static PackageManagerService main(Context context, Installer installer,
2256            boolean factoryTest, boolean onlyCore) {
2257        // Self-check for initial settings.
2258        PackageManagerServiceCompilerMapping.checkProperties();
2259
2260        PackageManagerService m = new PackageManagerService(context, installer,
2261                factoryTest, onlyCore);
2262        m.enableSystemUserPackages();
2263        ServiceManager.addService("package", m);
2264        final PackageManagerNative pmn = m.new PackageManagerNative();
2265        ServiceManager.addService("package_native", pmn);
2266        return m;
2267    }
2268
2269    private void enableSystemUserPackages() {
2270        if (!UserManager.isSplitSystemUser()) {
2271            return;
2272        }
2273        // For system user, enable apps based on the following conditions:
2274        // - app is whitelisted or belong to one of these groups:
2275        //   -- system app which has no launcher icons
2276        //   -- system app which has INTERACT_ACROSS_USERS permission
2277        //   -- system IME app
2278        // - app is not in the blacklist
2279        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2280        Set<String> enableApps = new ArraySet<>();
2281        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2282                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2283                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2284        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2285        enableApps.addAll(wlApps);
2286        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2287                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2288        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2289        enableApps.removeAll(blApps);
2290        Log.i(TAG, "Applications installed for system user: " + enableApps);
2291        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2292                UserHandle.SYSTEM);
2293        final int allAppsSize = allAps.size();
2294        synchronized (mPackages) {
2295            for (int i = 0; i < allAppsSize; i++) {
2296                String pName = allAps.get(i);
2297                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2298                // Should not happen, but we shouldn't be failing if it does
2299                if (pkgSetting == null) {
2300                    continue;
2301                }
2302                boolean install = enableApps.contains(pName);
2303                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2304                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2305                            + " for system user");
2306                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2307                }
2308            }
2309            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2310        }
2311    }
2312
2313    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2314        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2315                Context.DISPLAY_SERVICE);
2316        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2317    }
2318
2319    /**
2320     * Requests that files preopted on a secondary system partition be copied to the data partition
2321     * if possible.  Note that the actual copying of the files is accomplished by init for security
2322     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2323     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2324     */
2325    private static void requestCopyPreoptedFiles() {
2326        final int WAIT_TIME_MS = 100;
2327        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2328        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2329            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2330            // We will wait for up to 100 seconds.
2331            final long timeStart = SystemClock.uptimeMillis();
2332            final long timeEnd = timeStart + 100 * 1000;
2333            long timeNow = timeStart;
2334            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2335                try {
2336                    Thread.sleep(WAIT_TIME_MS);
2337                } catch (InterruptedException e) {
2338                    // Do nothing
2339                }
2340                timeNow = SystemClock.uptimeMillis();
2341                if (timeNow > timeEnd) {
2342                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2343                    Slog.wtf(TAG, "cppreopt did not finish!");
2344                    break;
2345                }
2346            }
2347
2348            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2349        }
2350    }
2351
2352    public PackageManagerService(Context context, Installer installer,
2353            boolean factoryTest, boolean onlyCore) {
2354        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2355        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2356        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2357                SystemClock.uptimeMillis());
2358
2359        if (mSdkVersion <= 0) {
2360            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2361        }
2362
2363        mContext = context;
2364
2365        mFactoryTest = factoryTest;
2366        mOnlyCore = onlyCore;
2367        mMetrics = new DisplayMetrics();
2368        mInstaller = installer;
2369
2370        // Create sub-components that provide services / data. Order here is important.
2371        synchronized (mInstallLock) {
2372        synchronized (mPackages) {
2373            // Expose private service for system components to use.
2374            LocalServices.addService(
2375                    PackageManagerInternal.class, new PackageManagerInternalImpl());
2376            sUserManager = new UserManagerService(context, this,
2377                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2378            mPermissionManager = PermissionManagerService.create(context,
2379                    new DefaultPermissionGrantedCallback() {
2380                        @Override
2381                        public void onDefaultRuntimePermissionsGranted(int userId) {
2382                            synchronized(mPackages) {
2383                                mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);
2384                            }
2385                        }
2386                    }, mPackages /*externalLock*/);
2387            mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy();
2388            mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages);
2389        }
2390        }
2391        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2392                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2393        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2394                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2395        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2396                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2397        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2398                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2399        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2400                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2401        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2402                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2403
2404        String separateProcesses = SystemProperties.get("debug.separate_processes");
2405        if (separateProcesses != null && separateProcesses.length() > 0) {
2406            if ("*".equals(separateProcesses)) {
2407                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2408                mSeparateProcesses = null;
2409                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2410            } else {
2411                mDefParseFlags = 0;
2412                mSeparateProcesses = separateProcesses.split(",");
2413                Slog.w(TAG, "Running with debug.separate_processes: "
2414                        + separateProcesses);
2415            }
2416        } else {
2417            mDefParseFlags = 0;
2418            mSeparateProcesses = null;
2419        }
2420
2421        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2422                "*dexopt*");
2423        DexManager.Listener dexManagerListener = DexLogger.getListener(this,
2424                installer, mInstallLock);
2425        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock,
2426                dexManagerListener);
2427        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2428
2429        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2430                FgThread.get().getLooper());
2431
2432        getDefaultDisplayMetrics(context, mMetrics);
2433
2434        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2435        SystemConfig systemConfig = SystemConfig.getInstance();
2436        mAvailableFeatures = systemConfig.getAvailableFeatures();
2437        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2438
2439        mProtectedPackages = new ProtectedPackages(mContext);
2440
2441        synchronized (mInstallLock) {
2442        // writer
2443        synchronized (mPackages) {
2444            mHandlerThread = new ServiceThread(TAG,
2445                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2446            mHandlerThread.start();
2447            mHandler = new PackageHandler(mHandlerThread.getLooper());
2448            mProcessLoggingHandler = new ProcessLoggingHandler();
2449            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2450            mInstantAppRegistry = new InstantAppRegistry(this);
2451
2452            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2453            final int builtInLibCount = libConfig.size();
2454            for (int i = 0; i < builtInLibCount; i++) {
2455                String name = libConfig.keyAt(i);
2456                String path = libConfig.valueAt(i);
2457                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2458                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2459            }
2460
2461            SELinuxMMAC.readInstallPolicy();
2462
2463            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2464            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2465            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2466
2467            // Clean up orphaned packages for which the code path doesn't exist
2468            // and they are an update to a system app - caused by bug/32321269
2469            final int packageSettingCount = mSettings.mPackages.size();
2470            for (int i = packageSettingCount - 1; i >= 0; i--) {
2471                PackageSetting ps = mSettings.mPackages.valueAt(i);
2472                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2473                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2474                    mSettings.mPackages.removeAt(i);
2475                    mSettings.enableSystemPackageLPw(ps.name);
2476                }
2477            }
2478
2479            if (mFirstBoot) {
2480                requestCopyPreoptedFiles();
2481            }
2482
2483            String customResolverActivity = Resources.getSystem().getString(
2484                    R.string.config_customResolverActivity);
2485            if (TextUtils.isEmpty(customResolverActivity)) {
2486                customResolverActivity = null;
2487            } else {
2488                mCustomResolverComponentName = ComponentName.unflattenFromString(
2489                        customResolverActivity);
2490            }
2491
2492            long startTime = SystemClock.uptimeMillis();
2493
2494            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2495                    startTime);
2496
2497            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2498            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2499
2500            if (bootClassPath == null) {
2501                Slog.w(TAG, "No BOOTCLASSPATH found!");
2502            }
2503
2504            if (systemServerClassPath == null) {
2505                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2506            }
2507
2508            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2509
2510            final VersionInfo ver = mSettings.getInternalVersion();
2511            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2512            if (mIsUpgrade) {
2513                logCriticalInfo(Log.INFO,
2514                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2515            }
2516
2517            // when upgrading from pre-M, promote system app permissions from install to runtime
2518            mPromoteSystemApps =
2519                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2520
2521            // When upgrading from pre-N, we need to handle package extraction like first boot,
2522            // as there is no profiling data available.
2523            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2524
2525            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2526
2527            // save off the names of pre-existing system packages prior to scanning; we don't
2528            // want to automatically grant runtime permissions for new system apps
2529            if (mPromoteSystemApps) {
2530                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2531                while (pkgSettingIter.hasNext()) {
2532                    PackageSetting ps = pkgSettingIter.next();
2533                    if (isSystemApp(ps)) {
2534                        mExistingSystemPackages.add(ps.name);
2535                    }
2536                }
2537            }
2538
2539            mCacheDir = preparePackageParserCache(mIsUpgrade);
2540
2541            // Set flag to monitor and not change apk file paths when
2542            // scanning install directories.
2543            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2544
2545            if (mIsUpgrade || mFirstBoot) {
2546                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2547            }
2548
2549            // Collect vendor overlay packages. (Do this before scanning any apps.)
2550            // For security and version matching reason, only consider
2551            // overlay packages if they reside in the right directory.
2552            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR),
2553                    mDefParseFlags
2554                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2555                    scanFlags
2556                    | SCAN_AS_SYSTEM
2557                    | SCAN_TRUSTED_OVERLAY,
2558                    0);
2559
2560            mParallelPackageParserCallback.findStaticOverlayPackages();
2561
2562            // Find base frameworks (resource packages without code).
2563            scanDirTracedLI(frameworkDir,
2564                    mDefParseFlags
2565                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2566                    scanFlags
2567                    | SCAN_NO_DEX
2568                    | SCAN_AS_SYSTEM
2569                    | SCAN_AS_PRIVILEGED,
2570                    0);
2571
2572            // Collected privileged system packages.
2573            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2574            scanDirTracedLI(privilegedAppDir,
2575                    mDefParseFlags
2576                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2577                    scanFlags
2578                    | SCAN_AS_SYSTEM
2579                    | SCAN_AS_PRIVILEGED,
2580                    0);
2581
2582            // Collect ordinary system packages.
2583            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2584            scanDirTracedLI(systemAppDir,
2585                    mDefParseFlags
2586                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2587                    scanFlags
2588                    | SCAN_AS_SYSTEM,
2589                    0);
2590
2591            // Collected privileged vendor packages.
2592                File privilegedVendorAppDir = new File(Environment.getVendorDirectory(),
2593                        "priv-app");
2594            try {
2595                privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile();
2596            } catch (IOException e) {
2597                // failed to look up canonical path, continue with original one
2598            }
2599            scanDirTracedLI(privilegedVendorAppDir,
2600                    mDefParseFlags
2601                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2602                    scanFlags
2603                    | SCAN_AS_SYSTEM
2604                    | SCAN_AS_VENDOR
2605                    | SCAN_AS_PRIVILEGED,
2606                    0);
2607
2608            // Collect ordinary vendor packages.
2609            File vendorAppDir = new File(Environment.getVendorDirectory(), "app");
2610            try {
2611                vendorAppDir = vendorAppDir.getCanonicalFile();
2612            } catch (IOException e) {
2613                // failed to look up canonical path, continue with original one
2614            }
2615            scanDirTracedLI(vendorAppDir,
2616                    mDefParseFlags
2617                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2618                    scanFlags
2619                    | SCAN_AS_SYSTEM
2620                    | SCAN_AS_VENDOR,
2621                    0);
2622
2623            // Collect all OEM packages.
2624            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2625            scanDirTracedLI(oemAppDir,
2626                    mDefParseFlags
2627                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2628                    scanFlags
2629                    | SCAN_AS_SYSTEM
2630                    | SCAN_AS_OEM,
2631                    0);
2632
2633            // Prune any system packages that no longer exist.
2634            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2635            // Stub packages must either be replaced with full versions in the /data
2636            // partition or be disabled.
2637            final List<String> stubSystemApps = new ArrayList<>();
2638            if (!mOnlyCore) {
2639                // do this first before mucking with mPackages for the "expecting better" case
2640                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2641                while (pkgIterator.hasNext()) {
2642                    final PackageParser.Package pkg = pkgIterator.next();
2643                    if (pkg.isStub) {
2644                        stubSystemApps.add(pkg.packageName);
2645                    }
2646                }
2647
2648                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2649                while (psit.hasNext()) {
2650                    PackageSetting ps = psit.next();
2651
2652                    /*
2653                     * If this is not a system app, it can't be a
2654                     * disable system app.
2655                     */
2656                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2657                        continue;
2658                    }
2659
2660                    /*
2661                     * If the package is scanned, it's not erased.
2662                     */
2663                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2664                    if (scannedPkg != null) {
2665                        /*
2666                         * If the system app is both scanned and in the
2667                         * disabled packages list, then it must have been
2668                         * added via OTA. Remove it from the currently
2669                         * scanned package so the previously user-installed
2670                         * application can be scanned.
2671                         */
2672                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2673                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2674                                    + ps.name + "; removing system app.  Last known codePath="
2675                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2676                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2677                                    + scannedPkg.getLongVersionCode());
2678                            removePackageLI(scannedPkg, true);
2679                            mExpectingBetter.put(ps.name, ps.codePath);
2680                        }
2681
2682                        continue;
2683                    }
2684
2685                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2686                        psit.remove();
2687                        logCriticalInfo(Log.WARN, "System package " + ps.name
2688                                + " no longer exists; it's data will be wiped");
2689                        // Actual deletion of code and data will be handled by later
2690                        // reconciliation step
2691                    } else {
2692                        // we still have a disabled system package, but, it still might have
2693                        // been removed. check the code path still exists and check there's
2694                        // still a package. the latter can happen if an OTA keeps the same
2695                        // code path, but, changes the package name.
2696                        final PackageSetting disabledPs =
2697                                mSettings.getDisabledSystemPkgLPr(ps.name);
2698                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2699                                || disabledPs.pkg == null) {
2700                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2701                        }
2702                    }
2703                }
2704            }
2705
2706            //look for any incomplete package installations
2707            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2708            for (int i = 0; i < deletePkgsList.size(); i++) {
2709                // Actual deletion of code and data will be handled by later
2710                // reconciliation step
2711                final String packageName = deletePkgsList.get(i).name;
2712                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2713                synchronized (mPackages) {
2714                    mSettings.removePackageLPw(packageName);
2715                }
2716            }
2717
2718            //delete tmp files
2719            deleteTempPackageFiles();
2720
2721            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2722
2723            // Remove any shared userIDs that have no associated packages
2724            mSettings.pruneSharedUsersLPw();
2725            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2726            final int systemPackagesCount = mPackages.size();
2727            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2728                    + " ms, packageCount: " + systemPackagesCount
2729                    + " , timePerPackage: "
2730                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2731                    + " , cached: " + cachedSystemApps);
2732            if (mIsUpgrade && systemPackagesCount > 0) {
2733                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2734                        ((int) systemScanTime) / systemPackagesCount);
2735            }
2736            if (!mOnlyCore) {
2737                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2738                        SystemClock.uptimeMillis());
2739                scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2740
2741                scanDirTracedLI(sDrmAppPrivateInstallDir, mDefParseFlags
2742                        | PackageParser.PARSE_FORWARD_LOCK,
2743                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2744
2745                // Remove disable package settings for updated system apps that were
2746                // removed via an OTA. If the update is no longer present, remove the
2747                // app completely. Otherwise, revoke their system privileges.
2748                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2749                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2750                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2751
2752                    final String msg;
2753                    if (deletedPkg == null) {
2754                        // should have found an update, but, we didn't; remove everything
2755                        msg = "Updated system package " + deletedAppName
2756                                + " no longer exists; removing its data";
2757                        // Actual deletion of code and data will be handled by later
2758                        // reconciliation step
2759                    } else {
2760                        // found an update; revoke system privileges
2761                        msg = "Updated system package + " + deletedAppName
2762                                + " no longer exists; revoking system privileges";
2763
2764                        // Don't do anything if a stub is removed from the system image. If
2765                        // we were to remove the uncompressed version from the /data partition,
2766                        // this is where it'd be done.
2767
2768                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2769                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2770                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2771                    }
2772                    logCriticalInfo(Log.WARN, msg);
2773                }
2774
2775                /*
2776                 * Make sure all system apps that we expected to appear on
2777                 * the userdata partition actually showed up. If they never
2778                 * appeared, crawl back and revive the system version.
2779                 */
2780                for (int i = 0; i < mExpectingBetter.size(); i++) {
2781                    final String packageName = mExpectingBetter.keyAt(i);
2782                    if (!mPackages.containsKey(packageName)) {
2783                        final File scanFile = mExpectingBetter.valueAt(i);
2784
2785                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2786                                + " but never showed up; reverting to system");
2787
2788                        final @ParseFlags int reparseFlags;
2789                        final @ScanFlags int rescanFlags;
2790                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2791                            reparseFlags =
2792                                    mDefParseFlags |
2793                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2794                            rescanFlags =
2795                                    scanFlags
2796                                    | SCAN_AS_SYSTEM
2797                                    | SCAN_AS_PRIVILEGED;
2798                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2799                            reparseFlags =
2800                                    mDefParseFlags |
2801                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2802                            rescanFlags =
2803                                    scanFlags
2804                                    | SCAN_AS_SYSTEM;
2805                        } else if (FileUtils.contains(privilegedVendorAppDir, scanFile)) {
2806                            reparseFlags =
2807                                    mDefParseFlags |
2808                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2809                            rescanFlags =
2810                                    scanFlags
2811                                    | SCAN_AS_SYSTEM
2812                                    | SCAN_AS_VENDOR
2813                                    | SCAN_AS_PRIVILEGED;
2814                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2815                            reparseFlags =
2816                                    mDefParseFlags |
2817                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2818                            rescanFlags =
2819                                    scanFlags
2820                                    | SCAN_AS_SYSTEM
2821                                    | SCAN_AS_VENDOR;
2822                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2823                            reparseFlags =
2824                                    mDefParseFlags |
2825                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2826                            rescanFlags =
2827                                    scanFlags
2828                                    | SCAN_AS_SYSTEM
2829                                    | SCAN_AS_OEM;
2830                        } else {
2831                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2832                            continue;
2833                        }
2834
2835                        mSettings.enableSystemPackageLPw(packageName);
2836
2837                        try {
2838                            scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null);
2839                        } catch (PackageManagerException e) {
2840                            Slog.e(TAG, "Failed to parse original system package: "
2841                                    + e.getMessage());
2842                        }
2843                    }
2844                }
2845
2846                // Uncompress and install any stubbed system applications.
2847                // This must be done last to ensure all stubs are replaced or disabled.
2848                decompressSystemApplications(stubSystemApps, scanFlags);
2849
2850                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2851                                - cachedSystemApps;
2852
2853                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2854                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2855                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2856                        + " ms, packageCount: " + dataPackagesCount
2857                        + " , timePerPackage: "
2858                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2859                        + " , cached: " + cachedNonSystemApps);
2860                if (mIsUpgrade && dataPackagesCount > 0) {
2861                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2862                            ((int) dataScanTime) / dataPackagesCount);
2863                }
2864            }
2865            mExpectingBetter.clear();
2866
2867            // Resolve the storage manager.
2868            mStorageManagerPackage = getStorageManagerPackageName();
2869
2870            // Resolve protected action filters. Only the setup wizard is allowed to
2871            // have a high priority filter for these actions.
2872            mSetupWizardPackage = getSetupWizardPackageName();
2873            if (mProtectedFilters.size() > 0) {
2874                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2875                    Slog.i(TAG, "No setup wizard;"
2876                        + " All protected intents capped to priority 0");
2877                }
2878                for (ActivityIntentInfo filter : mProtectedFilters) {
2879                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2880                        if (DEBUG_FILTERS) {
2881                            Slog.i(TAG, "Found setup wizard;"
2882                                + " allow priority " + filter.getPriority() + ";"
2883                                + " package: " + filter.activity.info.packageName
2884                                + " activity: " + filter.activity.className
2885                                + " priority: " + filter.getPriority());
2886                        }
2887                        // skip setup wizard; allow it to keep the high priority filter
2888                        continue;
2889                    }
2890                    if (DEBUG_FILTERS) {
2891                        Slog.i(TAG, "Protected action; cap priority to 0;"
2892                                + " package: " + filter.activity.info.packageName
2893                                + " activity: " + filter.activity.className
2894                                + " origPrio: " + filter.getPriority());
2895                    }
2896                    filter.setPriority(0);
2897                }
2898            }
2899            mDeferProtectedFilters = false;
2900            mProtectedFilters.clear();
2901
2902            // Now that we know all of the shared libraries, update all clients to have
2903            // the correct library paths.
2904            updateAllSharedLibrariesLPw(null);
2905
2906            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2907                // NOTE: We ignore potential failures here during a system scan (like
2908                // the rest of the commands above) because there's precious little we
2909                // can do about it. A settings error is reported, though.
2910                final List<String> changedAbiCodePath =
2911                        adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2912                if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
2913                    for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
2914                        final String codePathString = changedAbiCodePath.get(i);
2915                        try {
2916                            mInstaller.rmdex(codePathString,
2917                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
2918                        } catch (InstallerException ignored) {
2919                        }
2920                    }
2921                }
2922            }
2923
2924            // Now that we know all the packages we are keeping,
2925            // read and update their last usage times.
2926            mPackageUsage.read(mPackages);
2927            mCompilerStats.read();
2928
2929            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2930                    SystemClock.uptimeMillis());
2931            Slog.i(TAG, "Time to scan packages: "
2932                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2933                    + " seconds");
2934
2935            // If the platform SDK has changed since the last time we booted,
2936            // we need to re-grant app permission to catch any new ones that
2937            // appear.  This is really a hack, and means that apps can in some
2938            // cases get permissions that the user didn't initially explicitly
2939            // allow...  it would be nice to have some better way to handle
2940            // this situation.
2941            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
2942            if (sdkUpdated) {
2943                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2944                        + mSdkVersion + "; regranting permissions for internal storage");
2945            }
2946            mPermissionManager.updateAllPermissions(
2947                    StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(),
2948                    mPermissionCallback);
2949            ver.sdkVersion = mSdkVersion;
2950
2951            // If this is the first boot or an update from pre-M, and it is a normal
2952            // boot, then we need to initialize the default preferred apps across
2953            // all defined users.
2954            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2955                for (UserInfo user : sUserManager.getUsers(true)) {
2956                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2957                    applyFactoryDefaultBrowserLPw(user.id);
2958                    primeDomainVerificationsLPw(user.id);
2959                }
2960            }
2961
2962            // Prepare storage for system user really early during boot,
2963            // since core system apps like SettingsProvider and SystemUI
2964            // can't wait for user to start
2965            final int storageFlags;
2966            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2967                storageFlags = StorageManager.FLAG_STORAGE_DE;
2968            } else {
2969                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2970            }
2971            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2972                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2973                    true /* onlyCoreApps */);
2974            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2975                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
2976                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2977                traceLog.traceBegin("AppDataFixup");
2978                try {
2979                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2980                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2981                } catch (InstallerException e) {
2982                    Slog.w(TAG, "Trouble fixing GIDs", e);
2983                }
2984                traceLog.traceEnd();
2985
2986                traceLog.traceBegin("AppDataPrepare");
2987                if (deferPackages == null || deferPackages.isEmpty()) {
2988                    return;
2989                }
2990                int count = 0;
2991                for (String pkgName : deferPackages) {
2992                    PackageParser.Package pkg = null;
2993                    synchronized (mPackages) {
2994                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2995                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2996                            pkg = ps.pkg;
2997                        }
2998                    }
2999                    if (pkg != null) {
3000                        synchronized (mInstallLock) {
3001                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
3002                                    true /* maybeMigrateAppData */);
3003                        }
3004                        count++;
3005                    }
3006                }
3007                traceLog.traceEnd();
3008                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
3009            }, "prepareAppData");
3010
3011            // If this is first boot after an OTA, and a normal boot, then
3012            // we need to clear code cache directories.
3013            // Note that we do *not* clear the application profiles. These remain valid
3014            // across OTAs and are used to drive profile verification (post OTA) and
3015            // profile compilation (without waiting to collect a fresh set of profiles).
3016            if (mIsUpgrade && !onlyCore) {
3017                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
3018                for (int i = 0; i < mSettings.mPackages.size(); i++) {
3019                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
3020                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
3021                        // No apps are running this early, so no need to freeze
3022                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
3023                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3024                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3025                    }
3026                }
3027                ver.fingerprint = Build.FINGERPRINT;
3028            }
3029
3030            checkDefaultBrowser();
3031
3032            // clear only after permissions and other defaults have been updated
3033            mExistingSystemPackages.clear();
3034            mPromoteSystemApps = false;
3035
3036            // All the changes are done during package scanning.
3037            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3038
3039            // can downgrade to reader
3040            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3041            mSettings.writeLPr();
3042            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3043            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3044                    SystemClock.uptimeMillis());
3045
3046            if (!mOnlyCore) {
3047                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3048                mRequiredInstallerPackage = getRequiredInstallerLPr();
3049                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3050                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3051                if (mIntentFilterVerifierComponent != null) {
3052                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3053                            mIntentFilterVerifierComponent);
3054                } else {
3055                    mIntentFilterVerifier = null;
3056                }
3057                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3058                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3059                        SharedLibraryInfo.VERSION_UNDEFINED);
3060                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3061                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3062                        SharedLibraryInfo.VERSION_UNDEFINED);
3063            } else {
3064                mRequiredVerifierPackage = null;
3065                mRequiredInstallerPackage = null;
3066                mRequiredUninstallerPackage = null;
3067                mIntentFilterVerifierComponent = null;
3068                mIntentFilterVerifier = null;
3069                mServicesSystemSharedLibraryPackageName = null;
3070                mSharedSystemSharedLibraryPackageName = null;
3071            }
3072
3073            mInstallerService = new PackageInstallerService(context, this);
3074            mArtManagerService = new ArtManagerService(this, mInstaller, mInstallLock);
3075            final Pair<ComponentName, String> instantAppResolverComponent =
3076                    getInstantAppResolverLPr();
3077            if (instantAppResolverComponent != null) {
3078                if (DEBUG_EPHEMERAL) {
3079                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3080                }
3081                mInstantAppResolverConnection = new EphemeralResolverConnection(
3082                        mContext, instantAppResolverComponent.first,
3083                        instantAppResolverComponent.second);
3084                mInstantAppResolverSettingsComponent =
3085                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3086            } else {
3087                mInstantAppResolverConnection = null;
3088                mInstantAppResolverSettingsComponent = null;
3089            }
3090            updateInstantAppInstallerLocked(null);
3091
3092            // Read and update the usage of dex files.
3093            // Do this at the end of PM init so that all the packages have their
3094            // data directory reconciled.
3095            // At this point we know the code paths of the packages, so we can validate
3096            // the disk file and build the internal cache.
3097            // The usage file is expected to be small so loading and verifying it
3098            // should take a fairly small time compare to the other activities (e.g. package
3099            // scanning).
3100            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3101            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3102            for (int userId : currentUserIds) {
3103                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3104            }
3105            mDexManager.load(userPackages);
3106            if (mIsUpgrade) {
3107                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3108                        (int) (SystemClock.uptimeMillis() - startTime));
3109            }
3110        } // synchronized (mPackages)
3111        } // synchronized (mInstallLock)
3112
3113        // Now after opening every single application zip, make sure they
3114        // are all flushed.  Not really needed, but keeps things nice and
3115        // tidy.
3116        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3117        Runtime.getRuntime().gc();
3118        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3119
3120        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3121        FallbackCategoryProvider.loadFallbacks();
3122        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3123
3124        // The initial scanning above does many calls into installd while
3125        // holding the mPackages lock, but we're mostly interested in yelling
3126        // once we have a booted system.
3127        mInstaller.setWarnIfHeld(mPackages);
3128
3129        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3130    }
3131
3132    /**
3133     * Uncompress and install stub applications.
3134     * <p>In order to save space on the system partition, some applications are shipped in a
3135     * compressed form. In addition the compressed bits for the full application, the
3136     * system image contains a tiny stub comprised of only the Android manifest.
3137     * <p>During the first boot, attempt to uncompress and install the full application. If
3138     * the application can't be installed for any reason, disable the stub and prevent
3139     * uncompressing the full application during future boots.
3140     * <p>In order to forcefully attempt an installation of a full application, go to app
3141     * settings and enable the application.
3142     */
3143    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3144        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3145            final String pkgName = stubSystemApps.get(i);
3146            // skip if the system package is already disabled
3147            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3148                stubSystemApps.remove(i);
3149                continue;
3150            }
3151            // skip if the package isn't installed (?!); this should never happen
3152            final PackageParser.Package pkg = mPackages.get(pkgName);
3153            if (pkg == null) {
3154                stubSystemApps.remove(i);
3155                continue;
3156            }
3157            // skip if the package has been disabled by the user
3158            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3159            if (ps != null) {
3160                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3161                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3162                    stubSystemApps.remove(i);
3163                    continue;
3164                }
3165            }
3166
3167            if (DEBUG_COMPRESSION) {
3168                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3169            }
3170
3171            // uncompress the binary to its eventual destination on /data
3172            final File scanFile = decompressPackage(pkg);
3173            if (scanFile == null) {
3174                continue;
3175            }
3176
3177            // install the package to replace the stub on /system
3178            try {
3179                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3180                removePackageLI(pkg, true /*chatty*/);
3181                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3182                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3183                        UserHandle.USER_SYSTEM, "android");
3184                stubSystemApps.remove(i);
3185                continue;
3186            } catch (PackageManagerException e) {
3187                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3188            }
3189
3190            // any failed attempt to install the package will be cleaned up later
3191        }
3192
3193        // disable any stub still left; these failed to install the full application
3194        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3195            final String pkgName = stubSystemApps.get(i);
3196            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3197            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3198                    UserHandle.USER_SYSTEM, "android");
3199            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3200        }
3201    }
3202
3203    /**
3204     * Decompresses the given package on the system image onto
3205     * the /data partition.
3206     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3207     */
3208    private File decompressPackage(PackageParser.Package pkg) {
3209        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3210        if (compressedFiles == null || compressedFiles.length == 0) {
3211            if (DEBUG_COMPRESSION) {
3212                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3213            }
3214            return null;
3215        }
3216        final File dstCodePath =
3217                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3218        int ret = PackageManager.INSTALL_SUCCEEDED;
3219        try {
3220            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3221            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3222            for (File srcFile : compressedFiles) {
3223                final String srcFileName = srcFile.getName();
3224                final String dstFileName = srcFileName.substring(
3225                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3226                final File dstFile = new File(dstCodePath, dstFileName);
3227                ret = decompressFile(srcFile, dstFile);
3228                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3229                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3230                            + "; pkg: " + pkg.packageName
3231                            + ", file: " + dstFileName);
3232                    break;
3233                }
3234            }
3235        } catch (ErrnoException e) {
3236            logCriticalInfo(Log.ERROR, "Failed to decompress"
3237                    + "; pkg: " + pkg.packageName
3238                    + ", err: " + e.errno);
3239        }
3240        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3241            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3242            NativeLibraryHelper.Handle handle = null;
3243            try {
3244                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3245                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3246                        null /*abiOverride*/);
3247            } catch (IOException e) {
3248                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3249                        + "; pkg: " + pkg.packageName);
3250                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3251            } finally {
3252                IoUtils.closeQuietly(handle);
3253            }
3254        }
3255        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3256            if (dstCodePath == null || !dstCodePath.exists()) {
3257                return null;
3258            }
3259            removeCodePathLI(dstCodePath);
3260            return null;
3261        }
3262
3263        return dstCodePath;
3264    }
3265
3266    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3267        // we're only interested in updating the installer appliction when 1) it's not
3268        // already set or 2) the modified package is the installer
3269        if (mInstantAppInstallerActivity != null
3270                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3271                        .equals(modifiedPackage)) {
3272            return;
3273        }
3274        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3275    }
3276
3277    private static File preparePackageParserCache(boolean isUpgrade) {
3278        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3279            return null;
3280        }
3281
3282        // Disable package parsing on eng builds to allow for faster incremental development.
3283        if (Build.IS_ENG) {
3284            return null;
3285        }
3286
3287        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3288            Slog.i(TAG, "Disabling package parser cache due to system property.");
3289            return null;
3290        }
3291
3292        // The base directory for the package parser cache lives under /data/system/.
3293        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3294                "package_cache");
3295        if (cacheBaseDir == null) {
3296            return null;
3297        }
3298
3299        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3300        // This also serves to "GC" unused entries when the package cache version changes (which
3301        // can only happen during upgrades).
3302        if (isUpgrade) {
3303            FileUtils.deleteContents(cacheBaseDir);
3304        }
3305
3306
3307        // Return the versioned package cache directory. This is something like
3308        // "/data/system/package_cache/1"
3309        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3310
3311        // The following is a workaround to aid development on non-numbered userdebug
3312        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3313        // the system partition is newer.
3314        //
3315        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3316        // that starts with "eng." to signify that this is an engineering build and not
3317        // destined for release.
3318        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3319            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3320
3321            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3322            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3323            // in general and should not be used for production changes. In this specific case,
3324            // we know that they will work.
3325            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3326            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3327                FileUtils.deleteContents(cacheBaseDir);
3328                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3329            }
3330        }
3331
3332        return cacheDir;
3333    }
3334
3335    @Override
3336    public boolean isFirstBoot() {
3337        // allow instant applications
3338        return mFirstBoot;
3339    }
3340
3341    @Override
3342    public boolean isOnlyCoreApps() {
3343        // allow instant applications
3344        return mOnlyCore;
3345    }
3346
3347    @Override
3348    public boolean isUpgrade() {
3349        // allow instant applications
3350        // The system property allows testing ota flow when upgraded to the same image.
3351        return mIsUpgrade || SystemProperties.getBoolean(
3352                "persist.pm.mock-upgrade", false /* default */);
3353    }
3354
3355    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3356        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3357
3358        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3359                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3360                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3361        if (matches.size() == 1) {
3362            return matches.get(0).getComponentInfo().packageName;
3363        } else if (matches.size() == 0) {
3364            Log.e(TAG, "There should probably be a verifier, but, none were found");
3365            return null;
3366        }
3367        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3368    }
3369
3370    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3371        synchronized (mPackages) {
3372            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3373            if (libraryEntry == null) {
3374                throw new IllegalStateException("Missing required shared library:" + name);
3375            }
3376            return libraryEntry.apk;
3377        }
3378    }
3379
3380    private @NonNull String getRequiredInstallerLPr() {
3381        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3382        intent.addCategory(Intent.CATEGORY_DEFAULT);
3383        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3384
3385        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3386                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3387                UserHandle.USER_SYSTEM);
3388        if (matches.size() == 1) {
3389            ResolveInfo resolveInfo = matches.get(0);
3390            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3391                throw new RuntimeException("The installer must be a privileged app");
3392            }
3393            return matches.get(0).getComponentInfo().packageName;
3394        } else {
3395            throw new RuntimeException("There must be exactly one installer; found " + matches);
3396        }
3397    }
3398
3399    private @NonNull String getRequiredUninstallerLPr() {
3400        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3401        intent.addCategory(Intent.CATEGORY_DEFAULT);
3402        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3403
3404        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3405                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3406                UserHandle.USER_SYSTEM);
3407        if (resolveInfo == null ||
3408                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3409            throw new RuntimeException("There must be exactly one uninstaller; found "
3410                    + resolveInfo);
3411        }
3412        return resolveInfo.getComponentInfo().packageName;
3413    }
3414
3415    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3416        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3417
3418        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3419                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3420                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3421        ResolveInfo best = null;
3422        final int N = matches.size();
3423        for (int i = 0; i < N; i++) {
3424            final ResolveInfo cur = matches.get(i);
3425            final String packageName = cur.getComponentInfo().packageName;
3426            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3427                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3428                continue;
3429            }
3430
3431            if (best == null || cur.priority > best.priority) {
3432                best = cur;
3433            }
3434        }
3435
3436        if (best != null) {
3437            return best.getComponentInfo().getComponentName();
3438        }
3439        Slog.w(TAG, "Intent filter verifier not found");
3440        return null;
3441    }
3442
3443    @Override
3444    public @Nullable ComponentName getInstantAppResolverComponent() {
3445        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3446            return null;
3447        }
3448        synchronized (mPackages) {
3449            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3450            if (instantAppResolver == null) {
3451                return null;
3452            }
3453            return instantAppResolver.first;
3454        }
3455    }
3456
3457    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3458        final String[] packageArray =
3459                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3460        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3461            if (DEBUG_EPHEMERAL) {
3462                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3463            }
3464            return null;
3465        }
3466
3467        final int callingUid = Binder.getCallingUid();
3468        final int resolveFlags =
3469                MATCH_DIRECT_BOOT_AWARE
3470                | MATCH_DIRECT_BOOT_UNAWARE
3471                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3472        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3473        final Intent resolverIntent = new Intent(actionName);
3474        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3475                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3476        // temporarily look for the old action
3477        if (resolvers.size() == 0) {
3478            if (DEBUG_EPHEMERAL) {
3479                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3480            }
3481            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3482            resolverIntent.setAction(actionName);
3483            resolvers = queryIntentServicesInternal(resolverIntent, null,
3484                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3485        }
3486        final int N = resolvers.size();
3487        if (N == 0) {
3488            if (DEBUG_EPHEMERAL) {
3489                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3490            }
3491            return null;
3492        }
3493
3494        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3495        for (int i = 0; i < N; i++) {
3496            final ResolveInfo info = resolvers.get(i);
3497
3498            if (info.serviceInfo == null) {
3499                continue;
3500            }
3501
3502            final String packageName = info.serviceInfo.packageName;
3503            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3504                if (DEBUG_EPHEMERAL) {
3505                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3506                            + " pkg: " + packageName + ", info:" + info);
3507                }
3508                continue;
3509            }
3510
3511            if (DEBUG_EPHEMERAL) {
3512                Slog.v(TAG, "Ephemeral resolver found;"
3513                        + " pkg: " + packageName + ", info:" + info);
3514            }
3515            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3516        }
3517        if (DEBUG_EPHEMERAL) {
3518            Slog.v(TAG, "Ephemeral resolver NOT found");
3519        }
3520        return null;
3521    }
3522
3523    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3524        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3525        intent.addCategory(Intent.CATEGORY_DEFAULT);
3526        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3527
3528        final int resolveFlags =
3529                MATCH_DIRECT_BOOT_AWARE
3530                | MATCH_DIRECT_BOOT_UNAWARE
3531                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3532        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3533                resolveFlags, UserHandle.USER_SYSTEM);
3534        // temporarily look for the old action
3535        if (matches.isEmpty()) {
3536            if (DEBUG_EPHEMERAL) {
3537                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3538            }
3539            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3540            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3541                    resolveFlags, UserHandle.USER_SYSTEM);
3542        }
3543        Iterator<ResolveInfo> iter = matches.iterator();
3544        while (iter.hasNext()) {
3545            final ResolveInfo rInfo = iter.next();
3546            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3547            if (ps != null) {
3548                final PermissionsState permissionsState = ps.getPermissionsState();
3549                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3550                    continue;
3551                }
3552            }
3553            iter.remove();
3554        }
3555        if (matches.size() == 0) {
3556            return null;
3557        } else if (matches.size() == 1) {
3558            return (ActivityInfo) matches.get(0).getComponentInfo();
3559        } else {
3560            throw new RuntimeException(
3561                    "There must be at most one ephemeral installer; found " + matches);
3562        }
3563    }
3564
3565    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3566            @NonNull ComponentName resolver) {
3567        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3568                .addCategory(Intent.CATEGORY_DEFAULT)
3569                .setPackage(resolver.getPackageName());
3570        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3571        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3572                UserHandle.USER_SYSTEM);
3573        // temporarily look for the old action
3574        if (matches.isEmpty()) {
3575            if (DEBUG_EPHEMERAL) {
3576                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3577            }
3578            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3579            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3580                    UserHandle.USER_SYSTEM);
3581        }
3582        if (matches.isEmpty()) {
3583            return null;
3584        }
3585        return matches.get(0).getComponentInfo().getComponentName();
3586    }
3587
3588    private void primeDomainVerificationsLPw(int userId) {
3589        if (DEBUG_DOMAIN_VERIFICATION) {
3590            Slog.d(TAG, "Priming domain verifications in user " + userId);
3591        }
3592
3593        SystemConfig systemConfig = SystemConfig.getInstance();
3594        ArraySet<String> packages = systemConfig.getLinkedApps();
3595
3596        for (String packageName : packages) {
3597            PackageParser.Package pkg = mPackages.get(packageName);
3598            if (pkg != null) {
3599                if (!pkg.isSystem()) {
3600                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3601                    continue;
3602                }
3603
3604                ArraySet<String> domains = null;
3605                for (PackageParser.Activity a : pkg.activities) {
3606                    for (ActivityIntentInfo filter : a.intents) {
3607                        if (hasValidDomains(filter)) {
3608                            if (domains == null) {
3609                                domains = new ArraySet<String>();
3610                            }
3611                            domains.addAll(filter.getHostsList());
3612                        }
3613                    }
3614                }
3615
3616                if (domains != null && domains.size() > 0) {
3617                    if (DEBUG_DOMAIN_VERIFICATION) {
3618                        Slog.v(TAG, "      + " + packageName);
3619                    }
3620                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3621                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3622                    // and then 'always' in the per-user state actually used for intent resolution.
3623                    final IntentFilterVerificationInfo ivi;
3624                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3625                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3626                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3627                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3628                } else {
3629                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3630                            + "' does not handle web links");
3631                }
3632            } else {
3633                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3634            }
3635        }
3636
3637        scheduleWritePackageRestrictionsLocked(userId);
3638        scheduleWriteSettingsLocked();
3639    }
3640
3641    private void applyFactoryDefaultBrowserLPw(int userId) {
3642        // The default browser app's package name is stored in a string resource,
3643        // with a product-specific overlay used for vendor customization.
3644        String browserPkg = mContext.getResources().getString(
3645                com.android.internal.R.string.default_browser);
3646        if (!TextUtils.isEmpty(browserPkg)) {
3647            // non-empty string => required to be a known package
3648            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3649            if (ps == null) {
3650                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3651                browserPkg = null;
3652            } else {
3653                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3654            }
3655        }
3656
3657        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3658        // default.  If there's more than one, just leave everything alone.
3659        if (browserPkg == null) {
3660            calculateDefaultBrowserLPw(userId);
3661        }
3662    }
3663
3664    private void calculateDefaultBrowserLPw(int userId) {
3665        List<String> allBrowsers = resolveAllBrowserApps(userId);
3666        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3667        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3668    }
3669
3670    private List<String> resolveAllBrowserApps(int userId) {
3671        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3672        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3673                PackageManager.MATCH_ALL, userId);
3674
3675        final int count = list.size();
3676        List<String> result = new ArrayList<String>(count);
3677        for (int i=0; i<count; i++) {
3678            ResolveInfo info = list.get(i);
3679            if (info.activityInfo == null
3680                    || !info.handleAllWebDataURI
3681                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3682                    || result.contains(info.activityInfo.packageName)) {
3683                continue;
3684            }
3685            result.add(info.activityInfo.packageName);
3686        }
3687
3688        return result;
3689    }
3690
3691    private boolean packageIsBrowser(String packageName, int userId) {
3692        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3693                PackageManager.MATCH_ALL, userId);
3694        final int N = list.size();
3695        for (int i = 0; i < N; i++) {
3696            ResolveInfo info = list.get(i);
3697            if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) {
3698                return true;
3699            }
3700        }
3701        return false;
3702    }
3703
3704    private void checkDefaultBrowser() {
3705        final int myUserId = UserHandle.myUserId();
3706        final String packageName = getDefaultBrowserPackageName(myUserId);
3707        if (packageName != null) {
3708            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3709            if (info == null) {
3710                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3711                synchronized (mPackages) {
3712                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3713                }
3714            }
3715        }
3716    }
3717
3718    @Override
3719    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3720            throws RemoteException {
3721        try {
3722            return super.onTransact(code, data, reply, flags);
3723        } catch (RuntimeException e) {
3724            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3725                Slog.wtf(TAG, "Package Manager Crash", e);
3726            }
3727            throw e;
3728        }
3729    }
3730
3731    static int[] appendInts(int[] cur, int[] add) {
3732        if (add == null) return cur;
3733        if (cur == null) return add;
3734        final int N = add.length;
3735        for (int i=0; i<N; i++) {
3736            cur = appendInt(cur, add[i]);
3737        }
3738        return cur;
3739    }
3740
3741    /**
3742     * Returns whether or not a full application can see an instant application.
3743     * <p>
3744     * Currently, there are three cases in which this can occur:
3745     * <ol>
3746     * <li>The calling application is a "special" process. Special processes
3747     *     are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li>
3748     * <li>The calling application has the permission
3749     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li>
3750     * <li>The calling application is the default launcher on the
3751     *     system partition.</li>
3752     * </ol>
3753     */
3754    private boolean canViewInstantApps(int callingUid, int userId) {
3755        if (callingUid < Process.FIRST_APPLICATION_UID) {
3756            return true;
3757        }
3758        if (mContext.checkCallingOrSelfPermission(
3759                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3760            return true;
3761        }
3762        if (mContext.checkCallingOrSelfPermission(
3763                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3764            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3765            if (homeComponent != null
3766                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3767                return true;
3768            }
3769        }
3770        return false;
3771    }
3772
3773    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3774        if (!sUserManager.exists(userId)) return null;
3775        if (ps == null) {
3776            return null;
3777        }
3778        PackageParser.Package p = ps.pkg;
3779        if (p == null) {
3780            return null;
3781        }
3782        final int callingUid = Binder.getCallingUid();
3783        // Filter out ephemeral app metadata:
3784        //   * The system/shell/root can see metadata for any app
3785        //   * An installed app can see metadata for 1) other installed apps
3786        //     and 2) ephemeral apps that have explicitly interacted with it
3787        //   * Ephemeral apps can only see their own data and exposed installed apps
3788        //   * Holding a signature permission allows seeing instant apps
3789        if (filterAppAccessLPr(ps, callingUid, userId)) {
3790            return null;
3791        }
3792
3793        final PermissionsState permissionsState = ps.getPermissionsState();
3794
3795        // Compute GIDs only if requested
3796        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3797                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3798        // Compute granted permissions only if package has requested permissions
3799        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3800                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3801        final PackageUserState state = ps.readUserState(userId);
3802
3803        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3804                && ps.isSystem()) {
3805            flags |= MATCH_ANY_USER;
3806        }
3807
3808        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3809                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3810
3811        if (packageInfo == null) {
3812            return null;
3813        }
3814
3815        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3816                resolveExternalPackageNameLPr(p);
3817
3818        return packageInfo;
3819    }
3820
3821    @Override
3822    public void checkPackageStartable(String packageName, int userId) {
3823        final int callingUid = Binder.getCallingUid();
3824        if (getInstantAppPackageName(callingUid) != null) {
3825            throw new SecurityException("Instant applications don't have access to this method");
3826        }
3827        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3828        synchronized (mPackages) {
3829            final PackageSetting ps = mSettings.mPackages.get(packageName);
3830            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3831                throw new SecurityException("Package " + packageName + " was not found!");
3832            }
3833
3834            if (!ps.getInstalled(userId)) {
3835                throw new SecurityException(
3836                        "Package " + packageName + " was not installed for user " + userId + "!");
3837            }
3838
3839            if (mSafeMode && !ps.isSystem()) {
3840                throw new SecurityException("Package " + packageName + " not a system app!");
3841            }
3842
3843            if (mFrozenPackages.contains(packageName)) {
3844                throw new SecurityException("Package " + packageName + " is currently frozen!");
3845            }
3846
3847            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3848                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3849            }
3850        }
3851    }
3852
3853    @Override
3854    public boolean isPackageAvailable(String packageName, int userId) {
3855        if (!sUserManager.exists(userId)) return false;
3856        final int callingUid = Binder.getCallingUid();
3857        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
3858                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3859        synchronized (mPackages) {
3860            PackageParser.Package p = mPackages.get(packageName);
3861            if (p != null) {
3862                final PackageSetting ps = (PackageSetting) p.mExtras;
3863                if (filterAppAccessLPr(ps, callingUid, userId)) {
3864                    return false;
3865                }
3866                if (ps != null) {
3867                    final PackageUserState state = ps.readUserState(userId);
3868                    if (state != null) {
3869                        return PackageParser.isAvailable(state);
3870                    }
3871                }
3872            }
3873        }
3874        return false;
3875    }
3876
3877    @Override
3878    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3879        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3880                flags, Binder.getCallingUid(), userId);
3881    }
3882
3883    @Override
3884    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3885            int flags, int userId) {
3886        return getPackageInfoInternal(versionedPackage.getPackageName(),
3887                versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId);
3888    }
3889
3890    /**
3891     * Important: The provided filterCallingUid is used exclusively to filter out packages
3892     * that can be seen based on user state. It's typically the original caller uid prior
3893     * to clearing. Because it can only be provided by trusted code, it's value can be
3894     * trusted and will be used as-is; unlike userId which will be validated by this method.
3895     */
3896    private PackageInfo getPackageInfoInternal(String packageName, long versionCode,
3897            int flags, int filterCallingUid, int userId) {
3898        if (!sUserManager.exists(userId)) return null;
3899        flags = updateFlagsForPackage(flags, userId, packageName);
3900        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
3901                false /* requireFullPermission */, false /* checkShell */, "get package info");
3902
3903        // reader
3904        synchronized (mPackages) {
3905            // Normalize package name to handle renamed packages and static libs
3906            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3907
3908            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3909            if (matchFactoryOnly) {
3910                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3911                if (ps != null) {
3912                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3913                        return null;
3914                    }
3915                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3916                        return null;
3917                    }
3918                    return generatePackageInfo(ps, flags, userId);
3919                }
3920            }
3921
3922            PackageParser.Package p = mPackages.get(packageName);
3923            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3924                return null;
3925            }
3926            if (DEBUG_PACKAGE_INFO)
3927                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3928            if (p != null) {
3929                final PackageSetting ps = (PackageSetting) p.mExtras;
3930                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3931                    return null;
3932                }
3933                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3934                    return null;
3935                }
3936                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3937            }
3938            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3939                final PackageSetting ps = mSettings.mPackages.get(packageName);
3940                if (ps == null) return null;
3941                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3942                    return null;
3943                }
3944                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3945                    return null;
3946                }
3947                return generatePackageInfo(ps, flags, userId);
3948            }
3949        }
3950        return null;
3951    }
3952
3953    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3954        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3955            return true;
3956        }
3957        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3958            return true;
3959        }
3960        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3961            return true;
3962        }
3963        return false;
3964    }
3965
3966    private boolean isComponentVisibleToInstantApp(
3967            @Nullable ComponentName component, @ComponentType int type) {
3968        if (type == TYPE_ACTIVITY) {
3969            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3970            return activity != null
3971                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3972                    : false;
3973        } else if (type == TYPE_RECEIVER) {
3974            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3975            return activity != null
3976                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3977                    : false;
3978        } else if (type == TYPE_SERVICE) {
3979            final PackageParser.Service service = mServices.mServices.get(component);
3980            return service != null
3981                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3982                    : false;
3983        } else if (type == TYPE_PROVIDER) {
3984            final PackageParser.Provider provider = mProviders.mProviders.get(component);
3985            return provider != null
3986                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3987                    : false;
3988        } else if (type == TYPE_UNKNOWN) {
3989            return isComponentVisibleToInstantApp(component);
3990        }
3991        return false;
3992    }
3993
3994    /**
3995     * Returns whether or not access to the application should be filtered.
3996     * <p>
3997     * Access may be limited based upon whether the calling or target applications
3998     * are instant applications.
3999     *
4000     * @see #canAccessInstantApps(int)
4001     */
4002    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4003            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4004        // if we're in an isolated process, get the real calling UID
4005        if (Process.isIsolated(callingUid)) {
4006            callingUid = mIsolatedOwners.get(callingUid);
4007        }
4008        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4009        final boolean callerIsInstantApp = instantAppPkgName != null;
4010        if (ps == null) {
4011            if (callerIsInstantApp) {
4012                // pretend the application exists, but, needs to be filtered
4013                return true;
4014            }
4015            return false;
4016        }
4017        // if the target and caller are the same application, don't filter
4018        if (isCallerSameApp(ps.name, callingUid)) {
4019            return false;
4020        }
4021        if (callerIsInstantApp) {
4022            // request for a specific component; if it hasn't been explicitly exposed, filter
4023            if (component != null) {
4024                return !isComponentVisibleToInstantApp(component, componentType);
4025            }
4026            // request for application; if no components have been explicitly exposed, filter
4027            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4028        }
4029        if (ps.getInstantApp(userId)) {
4030            // caller can see all components of all instant applications, don't filter
4031            if (canViewInstantApps(callingUid, userId)) {
4032                return false;
4033            }
4034            // request for a specific instant application component, filter
4035            if (component != null) {
4036                return true;
4037            }
4038            // request for an instant application; if the caller hasn't been granted access, filter
4039            return !mInstantAppRegistry.isInstantAccessGranted(
4040                    userId, UserHandle.getAppId(callingUid), ps.appId);
4041        }
4042        return false;
4043    }
4044
4045    /**
4046     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4047     */
4048    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4049        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4050    }
4051
4052    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4053            int flags) {
4054        // Callers can access only the libs they depend on, otherwise they need to explicitly
4055        // ask for the shared libraries given the caller is allowed to access all static libs.
4056        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4057            // System/shell/root get to see all static libs
4058            final int appId = UserHandle.getAppId(uid);
4059            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4060                    || appId == Process.ROOT_UID) {
4061                return false;
4062            }
4063        }
4064
4065        // No package means no static lib as it is always on internal storage
4066        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4067            return false;
4068        }
4069
4070        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4071                ps.pkg.staticSharedLibVersion);
4072        if (libEntry == null) {
4073            return false;
4074        }
4075
4076        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4077        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4078        if (uidPackageNames == null) {
4079            return true;
4080        }
4081
4082        for (String uidPackageName : uidPackageNames) {
4083            if (ps.name.equals(uidPackageName)) {
4084                return false;
4085            }
4086            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4087            if (uidPs != null) {
4088                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4089                        libEntry.info.getName());
4090                if (index < 0) {
4091                    continue;
4092                }
4093                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) {
4094                    return false;
4095                }
4096            }
4097        }
4098        return true;
4099    }
4100
4101    @Override
4102    public String[] currentToCanonicalPackageNames(String[] names) {
4103        final int callingUid = Binder.getCallingUid();
4104        if (getInstantAppPackageName(callingUid) != null) {
4105            return names;
4106        }
4107        final String[] out = new String[names.length];
4108        // reader
4109        synchronized (mPackages) {
4110            final int callingUserId = UserHandle.getUserId(callingUid);
4111            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4112            for (int i=names.length-1; i>=0; i--) {
4113                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4114                boolean translateName = false;
4115                if (ps != null && ps.realName != null) {
4116                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4117                    translateName = !targetIsInstantApp
4118                            || canViewInstantApps
4119                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4120                                    UserHandle.getAppId(callingUid), ps.appId);
4121                }
4122                out[i] = translateName ? ps.realName : names[i];
4123            }
4124        }
4125        return out;
4126    }
4127
4128    @Override
4129    public String[] canonicalToCurrentPackageNames(String[] names) {
4130        final int callingUid = Binder.getCallingUid();
4131        if (getInstantAppPackageName(callingUid) != null) {
4132            return names;
4133        }
4134        final String[] out = new String[names.length];
4135        // reader
4136        synchronized (mPackages) {
4137            final int callingUserId = UserHandle.getUserId(callingUid);
4138            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4139            for (int i=names.length-1; i>=0; i--) {
4140                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4141                boolean translateName = false;
4142                if (cur != null) {
4143                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4144                    final boolean targetIsInstantApp =
4145                            ps != null && ps.getInstantApp(callingUserId);
4146                    translateName = !targetIsInstantApp
4147                            || canViewInstantApps
4148                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4149                                    UserHandle.getAppId(callingUid), ps.appId);
4150                }
4151                out[i] = translateName ? cur : names[i];
4152            }
4153        }
4154        return out;
4155    }
4156
4157    @Override
4158    public int getPackageUid(String packageName, int flags, int userId) {
4159        if (!sUserManager.exists(userId)) return -1;
4160        final int callingUid = Binder.getCallingUid();
4161        flags = updateFlagsForPackage(flags, userId, packageName);
4162        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4163                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4164
4165        // reader
4166        synchronized (mPackages) {
4167            final PackageParser.Package p = mPackages.get(packageName);
4168            if (p != null && p.isMatch(flags)) {
4169                PackageSetting ps = (PackageSetting) p.mExtras;
4170                if (filterAppAccessLPr(ps, callingUid, userId)) {
4171                    return -1;
4172                }
4173                return UserHandle.getUid(userId, p.applicationInfo.uid);
4174            }
4175            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4176                final PackageSetting ps = mSettings.mPackages.get(packageName);
4177                if (ps != null && ps.isMatch(flags)
4178                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4179                    return UserHandle.getUid(userId, ps.appId);
4180                }
4181            }
4182        }
4183
4184        return -1;
4185    }
4186
4187    @Override
4188    public int[] getPackageGids(String packageName, int flags, int userId) {
4189        if (!sUserManager.exists(userId)) return null;
4190        final int callingUid = Binder.getCallingUid();
4191        flags = updateFlagsForPackage(flags, userId, packageName);
4192        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4193                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4194
4195        // reader
4196        synchronized (mPackages) {
4197            final PackageParser.Package p = mPackages.get(packageName);
4198            if (p != null && p.isMatch(flags)) {
4199                PackageSetting ps = (PackageSetting) p.mExtras;
4200                if (filterAppAccessLPr(ps, callingUid, userId)) {
4201                    return null;
4202                }
4203                // TODO: Shouldn't this be checking for package installed state for userId and
4204                // return null?
4205                return ps.getPermissionsState().computeGids(userId);
4206            }
4207            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4208                final PackageSetting ps = mSettings.mPackages.get(packageName);
4209                if (ps != null && ps.isMatch(flags)
4210                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4211                    return ps.getPermissionsState().computeGids(userId);
4212                }
4213            }
4214        }
4215
4216        return null;
4217    }
4218
4219    @Override
4220    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4221        return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4222    }
4223
4224    @Override
4225    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4226            int flags) {
4227        final List<PermissionInfo> permissionList =
4228                mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid());
4229        return (permissionList == null) ? null : new ParceledListSlice<>(permissionList);
4230    }
4231
4232    @Override
4233    public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) {
4234        return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid());
4235    }
4236
4237    @Override
4238    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4239        final List<PermissionGroupInfo> permissionList =
4240                mPermissionManager.getAllPermissionGroups(flags, getCallingUid());
4241        return (permissionList == null)
4242                ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList);
4243    }
4244
4245    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4246            int filterCallingUid, int userId) {
4247        if (!sUserManager.exists(userId)) return null;
4248        PackageSetting ps = mSettings.mPackages.get(packageName);
4249        if (ps != null) {
4250            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4251                return null;
4252            }
4253            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4254                return null;
4255            }
4256            if (ps.pkg == null) {
4257                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4258                if (pInfo != null) {
4259                    return pInfo.applicationInfo;
4260                }
4261                return null;
4262            }
4263            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4264                    ps.readUserState(userId), userId);
4265            if (ai != null) {
4266                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4267            }
4268            return ai;
4269        }
4270        return null;
4271    }
4272
4273    @Override
4274    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4275        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4276    }
4277
4278    /**
4279     * Important: The provided filterCallingUid is used exclusively to filter out applications
4280     * that can be seen based on user state. It's typically the original caller uid prior
4281     * to clearing. Because it can only be provided by trusted code, it's value can be
4282     * trusted and will be used as-is; unlike userId which will be validated by this method.
4283     */
4284    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4285            int filterCallingUid, int userId) {
4286        if (!sUserManager.exists(userId)) return null;
4287        flags = updateFlagsForApplication(flags, userId, packageName);
4288        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4289                false /* requireFullPermission */, false /* checkShell */, "get application info");
4290
4291        // writer
4292        synchronized (mPackages) {
4293            // Normalize package name to handle renamed packages and static libs
4294            packageName = resolveInternalPackageNameLPr(packageName,
4295                    PackageManager.VERSION_CODE_HIGHEST);
4296
4297            PackageParser.Package p = mPackages.get(packageName);
4298            if (DEBUG_PACKAGE_INFO) Log.v(
4299                    TAG, "getApplicationInfo " + packageName
4300                    + ": " + p);
4301            if (p != null) {
4302                PackageSetting ps = mSettings.mPackages.get(packageName);
4303                if (ps == null) return null;
4304                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4305                    return null;
4306                }
4307                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4308                    return null;
4309                }
4310                // Note: isEnabledLP() does not apply here - always return info
4311                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4312                        p, flags, ps.readUserState(userId), userId);
4313                if (ai != null) {
4314                    ai.packageName = resolveExternalPackageNameLPr(p);
4315                }
4316                return ai;
4317            }
4318            if ("android".equals(packageName)||"system".equals(packageName)) {
4319                return mAndroidApplication;
4320            }
4321            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4322                // Already generates the external package name
4323                return generateApplicationInfoFromSettingsLPw(packageName,
4324                        flags, filterCallingUid, userId);
4325            }
4326        }
4327        return null;
4328    }
4329
4330    private String normalizePackageNameLPr(String packageName) {
4331        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4332        return normalizedPackageName != null ? normalizedPackageName : packageName;
4333    }
4334
4335    @Override
4336    public void deletePreloadsFileCache() {
4337        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4338            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4339        }
4340        File dir = Environment.getDataPreloadsFileCacheDirectory();
4341        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4342        FileUtils.deleteContents(dir);
4343    }
4344
4345    @Override
4346    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4347            final int storageFlags, final IPackageDataObserver observer) {
4348        mContext.enforceCallingOrSelfPermission(
4349                android.Manifest.permission.CLEAR_APP_CACHE, null);
4350        mHandler.post(() -> {
4351            boolean success = false;
4352            try {
4353                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4354                success = true;
4355            } catch (IOException e) {
4356                Slog.w(TAG, e);
4357            }
4358            if (observer != null) {
4359                try {
4360                    observer.onRemoveCompleted(null, success);
4361                } catch (RemoteException e) {
4362                    Slog.w(TAG, e);
4363                }
4364            }
4365        });
4366    }
4367
4368    @Override
4369    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4370            final int storageFlags, final IntentSender pi) {
4371        mContext.enforceCallingOrSelfPermission(
4372                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4373        mHandler.post(() -> {
4374            boolean success = false;
4375            try {
4376                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4377                success = true;
4378            } catch (IOException e) {
4379                Slog.w(TAG, e);
4380            }
4381            if (pi != null) {
4382                try {
4383                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4384                } catch (SendIntentException e) {
4385                    Slog.w(TAG, e);
4386                }
4387            }
4388        });
4389    }
4390
4391    /**
4392     * Blocking call to clear various types of cached data across the system
4393     * until the requested bytes are available.
4394     */
4395    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4396        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4397        final File file = storage.findPathForUuid(volumeUuid);
4398        if (file.getUsableSpace() >= bytes) return;
4399
4400        if (ENABLE_FREE_CACHE_V2) {
4401            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4402                    volumeUuid);
4403            final boolean aggressive = (storageFlags
4404                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4405            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4406
4407            // 1. Pre-flight to determine if we have any chance to succeed
4408            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4409            if (internalVolume && (aggressive || SystemProperties
4410                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4411                deletePreloadsFileCache();
4412                if (file.getUsableSpace() >= bytes) return;
4413            }
4414
4415            // 3. Consider parsed APK data (aggressive only)
4416            if (internalVolume && aggressive) {
4417                FileUtils.deleteContents(mCacheDir);
4418                if (file.getUsableSpace() >= bytes) return;
4419            }
4420
4421            // 4. Consider cached app data (above quotas)
4422            try {
4423                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4424                        Installer.FLAG_FREE_CACHE_V2);
4425            } catch (InstallerException ignored) {
4426            }
4427            if (file.getUsableSpace() >= bytes) return;
4428
4429            // 5. Consider shared libraries with refcount=0 and age>min cache period
4430            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4431                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4432                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4433                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4434                return;
4435            }
4436
4437            // 6. Consider dexopt output (aggressive only)
4438            // TODO: Implement
4439
4440            // 7. Consider installed instant apps unused longer than min cache period
4441            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4442                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4443                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4444                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4445                return;
4446            }
4447
4448            // 8. Consider cached app data (below quotas)
4449            try {
4450                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4451                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4452            } catch (InstallerException ignored) {
4453            }
4454            if (file.getUsableSpace() >= bytes) return;
4455
4456            // 9. Consider DropBox entries
4457            // TODO: Implement
4458
4459            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4460            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4461                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4462                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4463                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4464                return;
4465            }
4466        } else {
4467            try {
4468                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4469            } catch (InstallerException ignored) {
4470            }
4471            if (file.getUsableSpace() >= bytes) return;
4472        }
4473
4474        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4475    }
4476
4477    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4478            throws IOException {
4479        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4480        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4481
4482        List<VersionedPackage> packagesToDelete = null;
4483        final long now = System.currentTimeMillis();
4484
4485        synchronized (mPackages) {
4486            final int[] allUsers = sUserManager.getUserIds();
4487            final int libCount = mSharedLibraries.size();
4488            for (int i = 0; i < libCount; i++) {
4489                final LongSparseArray<SharedLibraryEntry> versionedLib
4490                        = mSharedLibraries.valueAt(i);
4491                if (versionedLib == null) {
4492                    continue;
4493                }
4494                final int versionCount = versionedLib.size();
4495                for (int j = 0; j < versionCount; j++) {
4496                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4497                    // Skip packages that are not static shared libs.
4498                    if (!libInfo.isStatic()) {
4499                        break;
4500                    }
4501                    // Important: We skip static shared libs used for some user since
4502                    // in such a case we need to keep the APK on the device. The check for
4503                    // a lib being used for any user is performed by the uninstall call.
4504                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4505                    // Resolve the package name - we use synthetic package names internally
4506                    final String internalPackageName = resolveInternalPackageNameLPr(
4507                            declaringPackage.getPackageName(),
4508                            declaringPackage.getLongVersionCode());
4509                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4510                    // Skip unused static shared libs cached less than the min period
4511                    // to prevent pruning a lib needed by a subsequently installed package.
4512                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4513                        continue;
4514                    }
4515                    if (packagesToDelete == null) {
4516                        packagesToDelete = new ArrayList<>();
4517                    }
4518                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4519                            declaringPackage.getLongVersionCode()));
4520                }
4521            }
4522        }
4523
4524        if (packagesToDelete != null) {
4525            final int packageCount = packagesToDelete.size();
4526            for (int i = 0; i < packageCount; i++) {
4527                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4528                // Delete the package synchronously (will fail of the lib used for any user).
4529                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(),
4530                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4531                                == PackageManager.DELETE_SUCCEEDED) {
4532                    if (volume.getUsableSpace() >= neededSpace) {
4533                        return true;
4534                    }
4535                }
4536            }
4537        }
4538
4539        return false;
4540    }
4541
4542    /**
4543     * Update given flags based on encryption status of current user.
4544     */
4545    private int updateFlags(int flags, int userId) {
4546        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4547                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4548            // Caller expressed an explicit opinion about what encryption
4549            // aware/unaware components they want to see, so fall through and
4550            // give them what they want
4551        } else {
4552            // Caller expressed no opinion, so match based on user state
4553            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4554                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4555            } else {
4556                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4557            }
4558        }
4559        return flags;
4560    }
4561
4562    private UserManagerInternal getUserManagerInternal() {
4563        if (mUserManagerInternal == null) {
4564            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4565        }
4566        return mUserManagerInternal;
4567    }
4568
4569    private DeviceIdleController.LocalService getDeviceIdleController() {
4570        if (mDeviceIdleController == null) {
4571            mDeviceIdleController =
4572                    LocalServices.getService(DeviceIdleController.LocalService.class);
4573        }
4574        return mDeviceIdleController;
4575    }
4576
4577    /**
4578     * Update given flags when being used to request {@link PackageInfo}.
4579     */
4580    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4581        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4582        boolean triaged = true;
4583        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4584                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4585            // Caller is asking for component details, so they'd better be
4586            // asking for specific encryption matching behavior, or be triaged
4587            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4588                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4589                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4590                triaged = false;
4591            }
4592        }
4593        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4594                | PackageManager.MATCH_SYSTEM_ONLY
4595                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4596            triaged = false;
4597        }
4598        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4599            mPermissionManager.enforceCrossUserPermission(
4600                    Binder.getCallingUid(), userId, false, false,
4601                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4602                    + Debug.getCallers(5));
4603        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4604                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4605            // If the caller wants all packages and has a restricted profile associated with it,
4606            // then match all users. This is to make sure that launchers that need to access work
4607            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4608            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4609            flags |= PackageManager.MATCH_ANY_USER;
4610        }
4611        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4612            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4613                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4614        }
4615        return updateFlags(flags, userId);
4616    }
4617
4618    /**
4619     * Update given flags when being used to request {@link ApplicationInfo}.
4620     */
4621    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4622        return updateFlagsForPackage(flags, userId, cookie);
4623    }
4624
4625    /**
4626     * Update given flags when being used to request {@link ComponentInfo}.
4627     */
4628    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4629        if (cookie instanceof Intent) {
4630            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4631                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4632            }
4633        }
4634
4635        boolean triaged = true;
4636        // Caller is asking for component details, so they'd better be
4637        // asking for specific encryption matching behavior, or be triaged
4638        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4639                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4640                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4641            triaged = false;
4642        }
4643        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4644            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4645                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4646        }
4647
4648        return updateFlags(flags, userId);
4649    }
4650
4651    /**
4652     * Update given intent when being used to request {@link ResolveInfo}.
4653     */
4654    private Intent updateIntentForResolve(Intent intent) {
4655        if (intent.getSelector() != null) {
4656            intent = intent.getSelector();
4657        }
4658        if (DEBUG_PREFERRED) {
4659            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4660        }
4661        return intent;
4662    }
4663
4664    /**
4665     * Update given flags when being used to request {@link ResolveInfo}.
4666     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4667     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4668     * flag set. However, this flag is only honoured in three circumstances:
4669     * <ul>
4670     * <li>when called from a system process</li>
4671     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4672     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4673     * action and a {@code android.intent.category.BROWSABLE} category</li>
4674     * </ul>
4675     */
4676    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4677        return updateFlagsForResolve(flags, userId, intent, callingUid,
4678                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4679    }
4680    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4681            boolean wantInstantApps) {
4682        return updateFlagsForResolve(flags, userId, intent, callingUid,
4683                wantInstantApps, false /*onlyExposedExplicitly*/);
4684    }
4685    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4686            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4687        // Safe mode means we shouldn't match any third-party components
4688        if (mSafeMode) {
4689            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4690        }
4691        if (getInstantAppPackageName(callingUid) != null) {
4692            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4693            if (onlyExposedExplicitly) {
4694                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4695            }
4696            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4697            flags |= PackageManager.MATCH_INSTANT;
4698        } else {
4699            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4700            final boolean allowMatchInstant =
4701                    (wantInstantApps
4702                            && Intent.ACTION_VIEW.equals(intent.getAction())
4703                            && hasWebURI(intent))
4704                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4705            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4706                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4707            if (!allowMatchInstant) {
4708                flags &= ~PackageManager.MATCH_INSTANT;
4709            }
4710        }
4711        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4712    }
4713
4714    @Override
4715    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4716        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4717    }
4718
4719    /**
4720     * Important: The provided filterCallingUid is used exclusively to filter out activities
4721     * that can be seen based on user state. It's typically the original caller uid prior
4722     * to clearing. Because it can only be provided by trusted code, it's value can be
4723     * trusted and will be used as-is; unlike userId which will be validated by this method.
4724     */
4725    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4726            int filterCallingUid, int userId) {
4727        if (!sUserManager.exists(userId)) return null;
4728        flags = updateFlagsForComponent(flags, userId, component);
4729        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4730                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4731        synchronized (mPackages) {
4732            PackageParser.Activity a = mActivities.mActivities.get(component);
4733
4734            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4735            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4736                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4737                if (ps == null) return null;
4738                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4739                    return null;
4740                }
4741                return PackageParser.generateActivityInfo(
4742                        a, flags, ps.readUserState(userId), userId);
4743            }
4744            if (mResolveComponentName.equals(component)) {
4745                return PackageParser.generateActivityInfo(
4746                        mResolveActivity, flags, new PackageUserState(), userId);
4747            }
4748        }
4749        return null;
4750    }
4751
4752    @Override
4753    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4754            String resolvedType) {
4755        synchronized (mPackages) {
4756            if (component.equals(mResolveComponentName)) {
4757                // The resolver supports EVERYTHING!
4758                return true;
4759            }
4760            final int callingUid = Binder.getCallingUid();
4761            final int callingUserId = UserHandle.getUserId(callingUid);
4762            PackageParser.Activity a = mActivities.mActivities.get(component);
4763            if (a == null) {
4764                return false;
4765            }
4766            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4767            if (ps == null) {
4768                return false;
4769            }
4770            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4771                return false;
4772            }
4773            for (int i=0; i<a.intents.size(); i++) {
4774                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4775                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4776                    return true;
4777                }
4778            }
4779            return false;
4780        }
4781    }
4782
4783    @Override
4784    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4785        if (!sUserManager.exists(userId)) return null;
4786        final int callingUid = Binder.getCallingUid();
4787        flags = updateFlagsForComponent(flags, userId, component);
4788        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4789                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4790        synchronized (mPackages) {
4791            PackageParser.Activity a = mReceivers.mActivities.get(component);
4792            if (DEBUG_PACKAGE_INFO) Log.v(
4793                TAG, "getReceiverInfo " + component + ": " + a);
4794            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4795                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4796                if (ps == null) return null;
4797                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4798                    return null;
4799                }
4800                return PackageParser.generateActivityInfo(
4801                        a, flags, ps.readUserState(userId), userId);
4802            }
4803        }
4804        return null;
4805    }
4806
4807    @Override
4808    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4809            int flags, int userId) {
4810        if (!sUserManager.exists(userId)) return null;
4811        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4812        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4813            return null;
4814        }
4815
4816        flags = updateFlagsForPackage(flags, userId, null);
4817
4818        final boolean canSeeStaticLibraries =
4819                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4820                        == PERMISSION_GRANTED
4821                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4822                        == PERMISSION_GRANTED
4823                || canRequestPackageInstallsInternal(packageName,
4824                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4825                        false  /* throwIfPermNotDeclared*/)
4826                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4827                        == PERMISSION_GRANTED;
4828
4829        synchronized (mPackages) {
4830            List<SharedLibraryInfo> result = null;
4831
4832            final int libCount = mSharedLibraries.size();
4833            for (int i = 0; i < libCount; i++) {
4834                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4835                if (versionedLib == null) {
4836                    continue;
4837                }
4838
4839                final int versionCount = versionedLib.size();
4840                for (int j = 0; j < versionCount; j++) {
4841                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4842                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4843                        break;
4844                    }
4845                    final long identity = Binder.clearCallingIdentity();
4846                    try {
4847                        PackageInfo packageInfo = getPackageInfoVersioned(
4848                                libInfo.getDeclaringPackage(), flags
4849                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4850                        if (packageInfo == null) {
4851                            continue;
4852                        }
4853                    } finally {
4854                        Binder.restoreCallingIdentity(identity);
4855                    }
4856
4857                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4858                            libInfo.getLongVersion(), libInfo.getType(),
4859                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4860                            flags, userId));
4861
4862                    if (result == null) {
4863                        result = new ArrayList<>();
4864                    }
4865                    result.add(resLibInfo);
4866                }
4867            }
4868
4869            return result != null ? new ParceledListSlice<>(result) : null;
4870        }
4871    }
4872
4873    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4874            SharedLibraryInfo libInfo, int flags, int userId) {
4875        List<VersionedPackage> versionedPackages = null;
4876        final int packageCount = mSettings.mPackages.size();
4877        for (int i = 0; i < packageCount; i++) {
4878            PackageSetting ps = mSettings.mPackages.valueAt(i);
4879
4880            if (ps == null) {
4881                continue;
4882            }
4883
4884            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4885                continue;
4886            }
4887
4888            final String libName = libInfo.getName();
4889            if (libInfo.isStatic()) {
4890                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4891                if (libIdx < 0) {
4892                    continue;
4893                }
4894                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) {
4895                    continue;
4896                }
4897                if (versionedPackages == null) {
4898                    versionedPackages = new ArrayList<>();
4899                }
4900                // If the dependent is a static shared lib, use the public package name
4901                String dependentPackageName = ps.name;
4902                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4903                    dependentPackageName = ps.pkg.manifestPackageName;
4904                }
4905                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4906            } else if (ps.pkg != null) {
4907                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4908                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4909                    if (versionedPackages == null) {
4910                        versionedPackages = new ArrayList<>();
4911                    }
4912                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4913                }
4914            }
4915        }
4916
4917        return versionedPackages;
4918    }
4919
4920    @Override
4921    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4922        if (!sUserManager.exists(userId)) return null;
4923        final int callingUid = Binder.getCallingUid();
4924        flags = updateFlagsForComponent(flags, userId, component);
4925        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4926                false /* requireFullPermission */, false /* checkShell */, "get service info");
4927        synchronized (mPackages) {
4928            PackageParser.Service s = mServices.mServices.get(component);
4929            if (DEBUG_PACKAGE_INFO) Log.v(
4930                TAG, "getServiceInfo " + component + ": " + s);
4931            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4932                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4933                if (ps == null) return null;
4934                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
4935                    return null;
4936                }
4937                return PackageParser.generateServiceInfo(
4938                        s, flags, ps.readUserState(userId), userId);
4939            }
4940        }
4941        return null;
4942    }
4943
4944    @Override
4945    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4946        if (!sUserManager.exists(userId)) return null;
4947        final int callingUid = Binder.getCallingUid();
4948        flags = updateFlagsForComponent(flags, userId, component);
4949        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4950                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4951        synchronized (mPackages) {
4952            PackageParser.Provider p = mProviders.mProviders.get(component);
4953            if (DEBUG_PACKAGE_INFO) Log.v(
4954                TAG, "getProviderInfo " + component + ": " + p);
4955            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4956                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4957                if (ps == null) return null;
4958                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
4959                    return null;
4960                }
4961                return PackageParser.generateProviderInfo(
4962                        p, flags, ps.readUserState(userId), userId);
4963            }
4964        }
4965        return null;
4966    }
4967
4968    @Override
4969    public String[] getSystemSharedLibraryNames() {
4970        // allow instant applications
4971        synchronized (mPackages) {
4972            Set<String> libs = null;
4973            final int libCount = mSharedLibraries.size();
4974            for (int i = 0; i < libCount; i++) {
4975                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4976                if (versionedLib == null) {
4977                    continue;
4978                }
4979                final int versionCount = versionedLib.size();
4980                for (int j = 0; j < versionCount; j++) {
4981                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4982                    if (!libEntry.info.isStatic()) {
4983                        if (libs == null) {
4984                            libs = new ArraySet<>();
4985                        }
4986                        libs.add(libEntry.info.getName());
4987                        break;
4988                    }
4989                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4990                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4991                            UserHandle.getUserId(Binder.getCallingUid()),
4992                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
4993                        if (libs == null) {
4994                            libs = new ArraySet<>();
4995                        }
4996                        libs.add(libEntry.info.getName());
4997                        break;
4998                    }
4999                }
5000            }
5001
5002            if (libs != null) {
5003                String[] libsArray = new String[libs.size()];
5004                libs.toArray(libsArray);
5005                return libsArray;
5006            }
5007
5008            return null;
5009        }
5010    }
5011
5012    @Override
5013    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5014        // allow instant applications
5015        synchronized (mPackages) {
5016            return mServicesSystemSharedLibraryPackageName;
5017        }
5018    }
5019
5020    @Override
5021    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5022        // allow instant applications
5023        synchronized (mPackages) {
5024            return mSharedSystemSharedLibraryPackageName;
5025        }
5026    }
5027
5028    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5029        for (int i = userList.length - 1; i >= 0; --i) {
5030            final int userId = userList[i];
5031            // don't add instant app to the list of updates
5032            if (pkgSetting.getInstantApp(userId)) {
5033                continue;
5034            }
5035            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5036            if (changedPackages == null) {
5037                changedPackages = new SparseArray<>();
5038                mChangedPackages.put(userId, changedPackages);
5039            }
5040            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5041            if (sequenceNumbers == null) {
5042                sequenceNumbers = new HashMap<>();
5043                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5044            }
5045            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5046            if (sequenceNumber != null) {
5047                changedPackages.remove(sequenceNumber);
5048            }
5049            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5050            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5051        }
5052        mChangedPackagesSequenceNumber++;
5053    }
5054
5055    @Override
5056    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5057        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5058            return null;
5059        }
5060        synchronized (mPackages) {
5061            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5062                return null;
5063            }
5064            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5065            if (changedPackages == null) {
5066                return null;
5067            }
5068            final List<String> packageNames =
5069                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5070            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5071                final String packageName = changedPackages.get(i);
5072                if (packageName != null) {
5073                    packageNames.add(packageName);
5074                }
5075            }
5076            return packageNames.isEmpty()
5077                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5078        }
5079    }
5080
5081    @Override
5082    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5083        // allow instant applications
5084        ArrayList<FeatureInfo> res;
5085        synchronized (mAvailableFeatures) {
5086            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5087            res.addAll(mAvailableFeatures.values());
5088        }
5089        final FeatureInfo fi = new FeatureInfo();
5090        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5091                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5092        res.add(fi);
5093
5094        return new ParceledListSlice<>(res);
5095    }
5096
5097    @Override
5098    public boolean hasSystemFeature(String name, int version) {
5099        // allow instant applications
5100        synchronized (mAvailableFeatures) {
5101            final FeatureInfo feat = mAvailableFeatures.get(name);
5102            if (feat == null) {
5103                return false;
5104            } else {
5105                return feat.version >= version;
5106            }
5107        }
5108    }
5109
5110    @Override
5111    public int checkPermission(String permName, String pkgName, int userId) {
5112        return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
5113    }
5114
5115    @Override
5116    public int checkUidPermission(String permName, int uid) {
5117        return mPermissionManager.checkUidPermission(permName, uid, getCallingUid());
5118    }
5119
5120    @Override
5121    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5122        if (UserHandle.getCallingUserId() != userId) {
5123            mContext.enforceCallingPermission(
5124                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5125                    "isPermissionRevokedByPolicy for user " + userId);
5126        }
5127
5128        if (checkPermission(permission, packageName, userId)
5129                == PackageManager.PERMISSION_GRANTED) {
5130            return false;
5131        }
5132
5133        final int callingUid = Binder.getCallingUid();
5134        if (getInstantAppPackageName(callingUid) != null) {
5135            if (!isCallerSameApp(packageName, callingUid)) {
5136                return false;
5137            }
5138        } else {
5139            if (isInstantApp(packageName, userId)) {
5140                return false;
5141            }
5142        }
5143
5144        final long identity = Binder.clearCallingIdentity();
5145        try {
5146            final int flags = getPermissionFlags(permission, packageName, userId);
5147            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5148        } finally {
5149            Binder.restoreCallingIdentity(identity);
5150        }
5151    }
5152
5153    @Override
5154    public String getPermissionControllerPackageName() {
5155        synchronized (mPackages) {
5156            return mRequiredInstallerPackage;
5157        }
5158    }
5159
5160    private boolean addDynamicPermission(PermissionInfo info, final boolean async) {
5161        return mPermissionManager.addDynamicPermission(
5162                info, async, getCallingUid(), new PermissionCallback() {
5163                    @Override
5164                    public void onPermissionChanged() {
5165                        if (!async) {
5166                            mSettings.writeLPr();
5167                        } else {
5168                            scheduleWriteSettingsLocked();
5169                        }
5170                    }
5171                });
5172    }
5173
5174    @Override
5175    public boolean addPermission(PermissionInfo info) {
5176        synchronized (mPackages) {
5177            return addDynamicPermission(info, false);
5178        }
5179    }
5180
5181    @Override
5182    public boolean addPermissionAsync(PermissionInfo info) {
5183        synchronized (mPackages) {
5184            return addDynamicPermission(info, true);
5185        }
5186    }
5187
5188    @Override
5189    public void removePermission(String permName) {
5190        mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback);
5191    }
5192
5193    @Override
5194    public void grantRuntimePermission(String packageName, String permName, final int userId) {
5195        mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
5196                getCallingUid(), userId, mPermissionCallback);
5197    }
5198
5199    @Override
5200    public void revokeRuntimePermission(String packageName, String permName, int userId) {
5201        mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
5202                getCallingUid(), userId, mPermissionCallback);
5203    }
5204
5205    @Override
5206    public void resetRuntimePermissions() {
5207        mContext.enforceCallingOrSelfPermission(
5208                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5209                "revokeRuntimePermission");
5210
5211        int callingUid = Binder.getCallingUid();
5212        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5213            mContext.enforceCallingOrSelfPermission(
5214                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5215                    "resetRuntimePermissions");
5216        }
5217
5218        synchronized (mPackages) {
5219            mPermissionManager.updateAllPermissions(
5220                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
5221                    mPermissionCallback);
5222            for (int userId : UserManagerService.getInstance().getUserIds()) {
5223                final int packageCount = mPackages.size();
5224                for (int i = 0; i < packageCount; i++) {
5225                    PackageParser.Package pkg = mPackages.valueAt(i);
5226                    if (!(pkg.mExtras instanceof PackageSetting)) {
5227                        continue;
5228                    }
5229                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5230                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5231                }
5232            }
5233        }
5234    }
5235
5236    @Override
5237    public int getPermissionFlags(String permName, String packageName, int userId) {
5238        return mPermissionManager.getPermissionFlags(
5239                permName, packageName, getCallingUid(), userId);
5240    }
5241
5242    @Override
5243    public void updatePermissionFlags(String permName, String packageName, int flagMask,
5244            int flagValues, int userId) {
5245        mPermissionManager.updatePermissionFlags(
5246                permName, packageName, flagMask, flagValues, getCallingUid(), userId,
5247                mPermissionCallback);
5248    }
5249
5250    /**
5251     * Update the permission flags for all packages and runtime permissions of a user in order
5252     * to allow device or profile owner to remove POLICY_FIXED.
5253     */
5254    @Override
5255    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5256        synchronized (mPackages) {
5257            final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5258                    flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5259                    mPermissionCallback);
5260            if (changed) {
5261                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5262            }
5263        }
5264    }
5265
5266    @Override
5267    public boolean shouldShowRequestPermissionRationale(String permissionName,
5268            String packageName, int userId) {
5269        if (UserHandle.getCallingUserId() != userId) {
5270            mContext.enforceCallingPermission(
5271                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5272                    "canShowRequestPermissionRationale for user " + userId);
5273        }
5274
5275        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5276        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5277            return false;
5278        }
5279
5280        if (checkPermission(permissionName, packageName, userId)
5281                == PackageManager.PERMISSION_GRANTED) {
5282            return false;
5283        }
5284
5285        final int flags;
5286
5287        final long identity = Binder.clearCallingIdentity();
5288        try {
5289            flags = getPermissionFlags(permissionName,
5290                    packageName, userId);
5291        } finally {
5292            Binder.restoreCallingIdentity(identity);
5293        }
5294
5295        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5296                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5297                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5298
5299        if ((flags & fixedFlags) != 0) {
5300            return false;
5301        }
5302
5303        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5304    }
5305
5306    @Override
5307    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5308        mContext.enforceCallingOrSelfPermission(
5309                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5310                "addOnPermissionsChangeListener");
5311
5312        synchronized (mPackages) {
5313            mOnPermissionChangeListeners.addListenerLocked(listener);
5314        }
5315    }
5316
5317    @Override
5318    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5319        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5320            throw new SecurityException("Instant applications don't have access to this method");
5321        }
5322        synchronized (mPackages) {
5323            mOnPermissionChangeListeners.removeListenerLocked(listener);
5324        }
5325    }
5326
5327    @Override
5328    public boolean isProtectedBroadcast(String actionName) {
5329        // allow instant applications
5330        synchronized (mProtectedBroadcasts) {
5331            if (mProtectedBroadcasts.contains(actionName)) {
5332                return true;
5333            } else if (actionName != null) {
5334                // TODO: remove these terrible hacks
5335                if (actionName.startsWith("android.net.netmon.lingerExpired")
5336                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5337                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5338                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5339                    return true;
5340                }
5341            }
5342        }
5343        return false;
5344    }
5345
5346    @Override
5347    public int checkSignatures(String pkg1, String pkg2) {
5348        synchronized (mPackages) {
5349            final PackageParser.Package p1 = mPackages.get(pkg1);
5350            final PackageParser.Package p2 = mPackages.get(pkg2);
5351            if (p1 == null || p1.mExtras == null
5352                    || p2 == null || p2.mExtras == null) {
5353                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5354            }
5355            final int callingUid = Binder.getCallingUid();
5356            final int callingUserId = UserHandle.getUserId(callingUid);
5357            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5358            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5359            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5360                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5361                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5362            }
5363            return compareSignatures(p1.mSignatures, p2.mSignatures);
5364        }
5365    }
5366
5367    @Override
5368    public int checkUidSignatures(int uid1, int uid2) {
5369        final int callingUid = Binder.getCallingUid();
5370        final int callingUserId = UserHandle.getUserId(callingUid);
5371        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5372        // Map to base uids.
5373        uid1 = UserHandle.getAppId(uid1);
5374        uid2 = UserHandle.getAppId(uid2);
5375        // reader
5376        synchronized (mPackages) {
5377            Signature[] s1;
5378            Signature[] s2;
5379            Object obj = mSettings.getUserIdLPr(uid1);
5380            if (obj != null) {
5381                if (obj instanceof SharedUserSetting) {
5382                    if (isCallerInstantApp) {
5383                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5384                    }
5385                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5386                } else if (obj instanceof PackageSetting) {
5387                    final PackageSetting ps = (PackageSetting) obj;
5388                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5389                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5390                    }
5391                    s1 = ps.signatures.mSignatures;
5392                } else {
5393                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5394                }
5395            } else {
5396                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5397            }
5398            obj = mSettings.getUserIdLPr(uid2);
5399            if (obj != null) {
5400                if (obj instanceof SharedUserSetting) {
5401                    if (isCallerInstantApp) {
5402                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5403                    }
5404                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5405                } else if (obj instanceof PackageSetting) {
5406                    final PackageSetting ps = (PackageSetting) obj;
5407                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5408                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5409                    }
5410                    s2 = ps.signatures.mSignatures;
5411                } else {
5412                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5413                }
5414            } else {
5415                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5416            }
5417            return compareSignatures(s1, s2);
5418        }
5419    }
5420
5421    /**
5422     * This method should typically only be used when granting or revoking
5423     * permissions, since the app may immediately restart after this call.
5424     * <p>
5425     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5426     * guard your work against the app being relaunched.
5427     */
5428    private void killUid(int appId, int userId, String reason) {
5429        final long identity = Binder.clearCallingIdentity();
5430        try {
5431            IActivityManager am = ActivityManager.getService();
5432            if (am != null) {
5433                try {
5434                    am.killUid(appId, userId, reason);
5435                } catch (RemoteException e) {
5436                    /* ignore - same process */
5437                }
5438            }
5439        } finally {
5440            Binder.restoreCallingIdentity(identity);
5441        }
5442    }
5443
5444    /**
5445     * If the database version for this type of package (internal storage or
5446     * external storage) is less than the version where package signatures
5447     * were updated, return true.
5448     */
5449    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5450        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5451        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5452    }
5453
5454    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5455        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5456        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5457    }
5458
5459    @Override
5460    public List<String> getAllPackages() {
5461        final int callingUid = Binder.getCallingUid();
5462        final int callingUserId = UserHandle.getUserId(callingUid);
5463        synchronized (mPackages) {
5464            if (canViewInstantApps(callingUid, callingUserId)) {
5465                return new ArrayList<String>(mPackages.keySet());
5466            }
5467            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5468            final List<String> result = new ArrayList<>();
5469            if (instantAppPkgName != null) {
5470                // caller is an instant application; filter unexposed applications
5471                for (PackageParser.Package pkg : mPackages.values()) {
5472                    if (!pkg.visibleToInstantApps) {
5473                        continue;
5474                    }
5475                    result.add(pkg.packageName);
5476                }
5477            } else {
5478                // caller is a normal application; filter instant applications
5479                for (PackageParser.Package pkg : mPackages.values()) {
5480                    final PackageSetting ps =
5481                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5482                    if (ps != null
5483                            && ps.getInstantApp(callingUserId)
5484                            && !mInstantAppRegistry.isInstantAccessGranted(
5485                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5486                        continue;
5487                    }
5488                    result.add(pkg.packageName);
5489                }
5490            }
5491            return result;
5492        }
5493    }
5494
5495    @Override
5496    public String[] getPackagesForUid(int uid) {
5497        final int callingUid = Binder.getCallingUid();
5498        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5499        final int userId = UserHandle.getUserId(uid);
5500        uid = UserHandle.getAppId(uid);
5501        // reader
5502        synchronized (mPackages) {
5503            Object obj = mSettings.getUserIdLPr(uid);
5504            if (obj instanceof SharedUserSetting) {
5505                if (isCallerInstantApp) {
5506                    return null;
5507                }
5508                final SharedUserSetting sus = (SharedUserSetting) obj;
5509                final int N = sus.packages.size();
5510                String[] res = new String[N];
5511                final Iterator<PackageSetting> it = sus.packages.iterator();
5512                int i = 0;
5513                while (it.hasNext()) {
5514                    PackageSetting ps = it.next();
5515                    if (ps.getInstalled(userId)) {
5516                        res[i++] = ps.name;
5517                    } else {
5518                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5519                    }
5520                }
5521                return res;
5522            } else if (obj instanceof PackageSetting) {
5523                final PackageSetting ps = (PackageSetting) obj;
5524                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5525                    return new String[]{ps.name};
5526                }
5527            }
5528        }
5529        return null;
5530    }
5531
5532    @Override
5533    public String getNameForUid(int uid) {
5534        final int callingUid = Binder.getCallingUid();
5535        if (getInstantAppPackageName(callingUid) != null) {
5536            return null;
5537        }
5538        synchronized (mPackages) {
5539            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5540            if (obj instanceof SharedUserSetting) {
5541                final SharedUserSetting sus = (SharedUserSetting) obj;
5542                return sus.name + ":" + sus.userId;
5543            } else if (obj instanceof PackageSetting) {
5544                final PackageSetting ps = (PackageSetting) obj;
5545                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5546                    return null;
5547                }
5548                return ps.name;
5549            }
5550            return null;
5551        }
5552    }
5553
5554    @Override
5555    public String[] getNamesForUids(int[] uids) {
5556        if (uids == null || uids.length == 0) {
5557            return null;
5558        }
5559        final int callingUid = Binder.getCallingUid();
5560        if (getInstantAppPackageName(callingUid) != null) {
5561            return null;
5562        }
5563        final String[] names = new String[uids.length];
5564        synchronized (mPackages) {
5565            for (int i = uids.length - 1; i >= 0; i--) {
5566                final int uid = uids[i];
5567                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5568                if (obj instanceof SharedUserSetting) {
5569                    final SharedUserSetting sus = (SharedUserSetting) obj;
5570                    names[i] = "shared:" + sus.name;
5571                } else if (obj instanceof PackageSetting) {
5572                    final PackageSetting ps = (PackageSetting) obj;
5573                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5574                        names[i] = null;
5575                    } else {
5576                        names[i] = ps.name;
5577                    }
5578                } else {
5579                    names[i] = null;
5580                }
5581            }
5582        }
5583        return names;
5584    }
5585
5586    @Override
5587    public int getUidForSharedUser(String sharedUserName) {
5588        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5589            return -1;
5590        }
5591        if (sharedUserName == null) {
5592            return -1;
5593        }
5594        // reader
5595        synchronized (mPackages) {
5596            SharedUserSetting suid;
5597            try {
5598                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5599                if (suid != null) {
5600                    return suid.userId;
5601                }
5602            } catch (PackageManagerException ignore) {
5603                // can't happen, but, still need to catch it
5604            }
5605            return -1;
5606        }
5607    }
5608
5609    @Override
5610    public int getFlagsForUid(int uid) {
5611        final int callingUid = Binder.getCallingUid();
5612        if (getInstantAppPackageName(callingUid) != null) {
5613            return 0;
5614        }
5615        synchronized (mPackages) {
5616            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5617            if (obj instanceof SharedUserSetting) {
5618                final SharedUserSetting sus = (SharedUserSetting) obj;
5619                return sus.pkgFlags;
5620            } else if (obj instanceof PackageSetting) {
5621                final PackageSetting ps = (PackageSetting) obj;
5622                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5623                    return 0;
5624                }
5625                return ps.pkgFlags;
5626            }
5627        }
5628        return 0;
5629    }
5630
5631    @Override
5632    public int getPrivateFlagsForUid(int uid) {
5633        final int callingUid = Binder.getCallingUid();
5634        if (getInstantAppPackageName(callingUid) != null) {
5635            return 0;
5636        }
5637        synchronized (mPackages) {
5638            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5639            if (obj instanceof SharedUserSetting) {
5640                final SharedUserSetting sus = (SharedUserSetting) obj;
5641                return sus.pkgPrivateFlags;
5642            } else if (obj instanceof PackageSetting) {
5643                final PackageSetting ps = (PackageSetting) obj;
5644                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5645                    return 0;
5646                }
5647                return ps.pkgPrivateFlags;
5648            }
5649        }
5650        return 0;
5651    }
5652
5653    @Override
5654    public boolean isUidPrivileged(int uid) {
5655        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5656            return false;
5657        }
5658        uid = UserHandle.getAppId(uid);
5659        // reader
5660        synchronized (mPackages) {
5661            Object obj = mSettings.getUserIdLPr(uid);
5662            if (obj instanceof SharedUserSetting) {
5663                final SharedUserSetting sus = (SharedUserSetting) obj;
5664                final Iterator<PackageSetting> it = sus.packages.iterator();
5665                while (it.hasNext()) {
5666                    if (it.next().isPrivileged()) {
5667                        return true;
5668                    }
5669                }
5670            } else if (obj instanceof PackageSetting) {
5671                final PackageSetting ps = (PackageSetting) obj;
5672                return ps.isPrivileged();
5673            }
5674        }
5675        return false;
5676    }
5677
5678    @Override
5679    public String[] getAppOpPermissionPackages(String permName) {
5680        return mPermissionManager.getAppOpPermissionPackages(permName);
5681    }
5682
5683    @Override
5684    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5685            int flags, int userId) {
5686        return resolveIntentInternal(
5687                intent, resolvedType, flags, userId, false /*resolveForStart*/);
5688    }
5689
5690    /**
5691     * Normally instant apps can only be resolved when they're visible to the caller.
5692     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
5693     * since we need to allow the system to start any installed application.
5694     */
5695    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5696            int flags, int userId, boolean resolveForStart) {
5697        try {
5698            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5699
5700            if (!sUserManager.exists(userId)) return null;
5701            final int callingUid = Binder.getCallingUid();
5702            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
5703            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5704                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5705
5706            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5707            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5708                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
5709            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5710
5711            final ResolveInfo bestChoice =
5712                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5713            return bestChoice;
5714        } finally {
5715            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5716        }
5717    }
5718
5719    @Override
5720    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5721        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5722            throw new SecurityException(
5723                    "findPersistentPreferredActivity can only be run by the system");
5724        }
5725        if (!sUserManager.exists(userId)) {
5726            return null;
5727        }
5728        final int callingUid = Binder.getCallingUid();
5729        intent = updateIntentForResolve(intent);
5730        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5731        final int flags = updateFlagsForResolve(
5732                0, userId, intent, callingUid, false /*includeInstantApps*/);
5733        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5734                userId);
5735        synchronized (mPackages) {
5736            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5737                    userId);
5738        }
5739    }
5740
5741    @Override
5742    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5743            IntentFilter filter, int match, ComponentName activity) {
5744        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5745            return;
5746        }
5747        final int userId = UserHandle.getCallingUserId();
5748        if (DEBUG_PREFERRED) {
5749            Log.v(TAG, "setLastChosenActivity intent=" + intent
5750                + " resolvedType=" + resolvedType
5751                + " flags=" + flags
5752                + " filter=" + filter
5753                + " match=" + match
5754                + " activity=" + activity);
5755            filter.dump(new PrintStreamPrinter(System.out), "    ");
5756        }
5757        intent.setComponent(null);
5758        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5759                userId);
5760        // Find any earlier preferred or last chosen entries and nuke them
5761        findPreferredActivity(intent, resolvedType,
5762                flags, query, 0, false, true, false, userId);
5763        // Add the new activity as the last chosen for this filter
5764        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5765                "Setting last chosen");
5766    }
5767
5768    @Override
5769    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5770        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5771            return null;
5772        }
5773        final int userId = UserHandle.getCallingUserId();
5774        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5775        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5776                userId);
5777        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5778                false, false, false, userId);
5779    }
5780
5781    /**
5782     * Returns whether or not instant apps have been disabled remotely.
5783     */
5784    private boolean isEphemeralDisabled() {
5785        return mEphemeralAppsDisabled;
5786    }
5787
5788    private boolean isInstantAppAllowed(
5789            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5790            boolean skipPackageCheck) {
5791        if (mInstantAppResolverConnection == null) {
5792            return false;
5793        }
5794        if (mInstantAppInstallerActivity == null) {
5795            return false;
5796        }
5797        if (intent.getComponent() != null) {
5798            return false;
5799        }
5800        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5801            return false;
5802        }
5803        if (!skipPackageCheck && intent.getPackage() != null) {
5804            return false;
5805        }
5806        final boolean isWebUri = hasWebURI(intent);
5807        if (!isWebUri || intent.getData().getHost() == null) {
5808            return false;
5809        }
5810        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5811        // Or if there's already an ephemeral app installed that handles the action
5812        synchronized (mPackages) {
5813            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5814            for (int n = 0; n < count; n++) {
5815                final ResolveInfo info = resolvedActivities.get(n);
5816                final String packageName = info.activityInfo.packageName;
5817                final PackageSetting ps = mSettings.mPackages.get(packageName);
5818                if (ps != null) {
5819                    // only check domain verification status if the app is not a browser
5820                    if (!info.handleAllWebDataURI) {
5821                        // Try to get the status from User settings first
5822                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5823                        final int status = (int) (packedStatus >> 32);
5824                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5825                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5826                            if (DEBUG_EPHEMERAL) {
5827                                Slog.v(TAG, "DENY instant app;"
5828                                    + " pkg: " + packageName + ", status: " + status);
5829                            }
5830                            return false;
5831                        }
5832                    }
5833                    if (ps.getInstantApp(userId)) {
5834                        if (DEBUG_EPHEMERAL) {
5835                            Slog.v(TAG, "DENY instant app installed;"
5836                                    + " pkg: " + packageName);
5837                        }
5838                        return false;
5839                    }
5840                }
5841            }
5842        }
5843        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5844        return true;
5845    }
5846
5847    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
5848            Intent origIntent, String resolvedType, String callingPackage,
5849            Bundle verificationBundle, int userId) {
5850        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
5851                new InstantAppRequest(responseObj, origIntent, resolvedType,
5852                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
5853        mHandler.sendMessage(msg);
5854    }
5855
5856    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5857            int flags, List<ResolveInfo> query, int userId) {
5858        if (query != null) {
5859            final int N = query.size();
5860            if (N == 1) {
5861                return query.get(0);
5862            } else if (N > 1) {
5863                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5864                // If there is more than one activity with the same priority,
5865                // then let the user decide between them.
5866                ResolveInfo r0 = query.get(0);
5867                ResolveInfo r1 = query.get(1);
5868                if (DEBUG_INTENT_MATCHING || debug) {
5869                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5870                            + r1.activityInfo.name + "=" + r1.priority);
5871                }
5872                // If the first activity has a higher priority, or a different
5873                // default, then it is always desirable to pick it.
5874                if (r0.priority != r1.priority
5875                        || r0.preferredOrder != r1.preferredOrder
5876                        || r0.isDefault != r1.isDefault) {
5877                    return query.get(0);
5878                }
5879                // If we have saved a preference for a preferred activity for
5880                // this Intent, use that.
5881                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5882                        flags, query, r0.priority, true, false, debug, userId);
5883                if (ri != null) {
5884                    return ri;
5885                }
5886                // If we have an ephemeral app, use it
5887                for (int i = 0; i < N; i++) {
5888                    ri = query.get(i);
5889                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
5890                        final String packageName = ri.activityInfo.packageName;
5891                        final PackageSetting ps = mSettings.mPackages.get(packageName);
5892                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5893                        final int status = (int)(packedStatus >> 32);
5894                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5895                            return ri;
5896                        }
5897                    }
5898                }
5899                ri = new ResolveInfo(mResolveInfo);
5900                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5901                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5902                // If all of the options come from the same package, show the application's
5903                // label and icon instead of the generic resolver's.
5904                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5905                // and then throw away the ResolveInfo itself, meaning that the caller loses
5906                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5907                // a fallback for this case; we only set the target package's resources on
5908                // the ResolveInfo, not the ActivityInfo.
5909                final String intentPackage = intent.getPackage();
5910                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5911                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5912                    ri.resolvePackageName = intentPackage;
5913                    if (userNeedsBadging(userId)) {
5914                        ri.noResourceId = true;
5915                    } else {
5916                        ri.icon = appi.icon;
5917                    }
5918                    ri.iconResourceId = appi.icon;
5919                    ri.labelRes = appi.labelRes;
5920                }
5921                ri.activityInfo.applicationInfo = new ApplicationInfo(
5922                        ri.activityInfo.applicationInfo);
5923                if (userId != 0) {
5924                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5925                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5926                }
5927                // Make sure that the resolver is displayable in car mode
5928                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5929                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5930                return ri;
5931            }
5932        }
5933        return null;
5934    }
5935
5936    /**
5937     * Return true if the given list is not empty and all of its contents have
5938     * an activityInfo with the given package name.
5939     */
5940    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5941        if (ArrayUtils.isEmpty(list)) {
5942            return false;
5943        }
5944        for (int i = 0, N = list.size(); i < N; i++) {
5945            final ResolveInfo ri = list.get(i);
5946            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5947            if (ai == null || !packageName.equals(ai.packageName)) {
5948                return false;
5949            }
5950        }
5951        return true;
5952    }
5953
5954    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5955            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5956        final int N = query.size();
5957        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5958                .get(userId);
5959        // Get the list of persistent preferred activities that handle the intent
5960        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5961        List<PersistentPreferredActivity> pprefs = ppir != null
5962                ? ppir.queryIntent(intent, resolvedType,
5963                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5964                        userId)
5965                : null;
5966        if (pprefs != null && pprefs.size() > 0) {
5967            final int M = pprefs.size();
5968            for (int i=0; i<M; i++) {
5969                final PersistentPreferredActivity ppa = pprefs.get(i);
5970                if (DEBUG_PREFERRED || debug) {
5971                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5972                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5973                            + "\n  component=" + ppa.mComponent);
5974                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5975                }
5976                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5977                        flags | MATCH_DISABLED_COMPONENTS, userId);
5978                if (DEBUG_PREFERRED || debug) {
5979                    Slog.v(TAG, "Found persistent preferred activity:");
5980                    if (ai != null) {
5981                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5982                    } else {
5983                        Slog.v(TAG, "  null");
5984                    }
5985                }
5986                if (ai == null) {
5987                    // This previously registered persistent preferred activity
5988                    // component is no longer known. Ignore it and do NOT remove it.
5989                    continue;
5990                }
5991                for (int j=0; j<N; j++) {
5992                    final ResolveInfo ri = query.get(j);
5993                    if (!ri.activityInfo.applicationInfo.packageName
5994                            .equals(ai.applicationInfo.packageName)) {
5995                        continue;
5996                    }
5997                    if (!ri.activityInfo.name.equals(ai.name)) {
5998                        continue;
5999                    }
6000                    //  Found a persistent preference that can handle the intent.
6001                    if (DEBUG_PREFERRED || debug) {
6002                        Slog.v(TAG, "Returning persistent preferred activity: " +
6003                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6004                    }
6005                    return ri;
6006                }
6007            }
6008        }
6009        return null;
6010    }
6011
6012    // TODO: handle preferred activities missing while user has amnesia
6013    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6014            List<ResolveInfo> query, int priority, boolean always,
6015            boolean removeMatches, boolean debug, int userId) {
6016        if (!sUserManager.exists(userId)) return null;
6017        final int callingUid = Binder.getCallingUid();
6018        flags = updateFlagsForResolve(
6019                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6020        intent = updateIntentForResolve(intent);
6021        // writer
6022        synchronized (mPackages) {
6023            // Try to find a matching persistent preferred activity.
6024            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6025                    debug, userId);
6026
6027            // If a persistent preferred activity matched, use it.
6028            if (pri != null) {
6029                return pri;
6030            }
6031
6032            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6033            // Get the list of preferred activities that handle the intent
6034            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6035            List<PreferredActivity> prefs = pir != null
6036                    ? pir.queryIntent(intent, resolvedType,
6037                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6038                            userId)
6039                    : null;
6040            if (prefs != null && prefs.size() > 0) {
6041                boolean changed = false;
6042                try {
6043                    // First figure out how good the original match set is.
6044                    // We will only allow preferred activities that came
6045                    // from the same match quality.
6046                    int match = 0;
6047
6048                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6049
6050                    final int N = query.size();
6051                    for (int j=0; j<N; j++) {
6052                        final ResolveInfo ri = query.get(j);
6053                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6054                                + ": 0x" + Integer.toHexString(match));
6055                        if (ri.match > match) {
6056                            match = ri.match;
6057                        }
6058                    }
6059
6060                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6061                            + Integer.toHexString(match));
6062
6063                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6064                    final int M = prefs.size();
6065                    for (int i=0; i<M; i++) {
6066                        final PreferredActivity pa = prefs.get(i);
6067                        if (DEBUG_PREFERRED || debug) {
6068                            Slog.v(TAG, "Checking PreferredActivity ds="
6069                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6070                                    + "\n  component=" + pa.mPref.mComponent);
6071                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6072                        }
6073                        if (pa.mPref.mMatch != match) {
6074                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6075                                    + Integer.toHexString(pa.mPref.mMatch));
6076                            continue;
6077                        }
6078                        // If it's not an "always" type preferred activity and that's what we're
6079                        // looking for, skip it.
6080                        if (always && !pa.mPref.mAlways) {
6081                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6082                            continue;
6083                        }
6084                        final ActivityInfo ai = getActivityInfo(
6085                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6086                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6087                                userId);
6088                        if (DEBUG_PREFERRED || debug) {
6089                            Slog.v(TAG, "Found preferred activity:");
6090                            if (ai != null) {
6091                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6092                            } else {
6093                                Slog.v(TAG, "  null");
6094                            }
6095                        }
6096                        if (ai == null) {
6097                            // This previously registered preferred activity
6098                            // component is no longer known.  Most likely an update
6099                            // to the app was installed and in the new version this
6100                            // component no longer exists.  Clean it up by removing
6101                            // it from the preferred activities list, and skip it.
6102                            Slog.w(TAG, "Removing dangling preferred activity: "
6103                                    + pa.mPref.mComponent);
6104                            pir.removeFilter(pa);
6105                            changed = true;
6106                            continue;
6107                        }
6108                        for (int j=0; j<N; j++) {
6109                            final ResolveInfo ri = query.get(j);
6110                            if (!ri.activityInfo.applicationInfo.packageName
6111                                    .equals(ai.applicationInfo.packageName)) {
6112                                continue;
6113                            }
6114                            if (!ri.activityInfo.name.equals(ai.name)) {
6115                                continue;
6116                            }
6117
6118                            if (removeMatches) {
6119                                pir.removeFilter(pa);
6120                                changed = true;
6121                                if (DEBUG_PREFERRED) {
6122                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6123                                }
6124                                break;
6125                            }
6126
6127                            // Okay we found a previously set preferred or last chosen app.
6128                            // If the result set is different from when this
6129                            // was created, and is not a subset of the preferred set, we need to
6130                            // clear it and re-ask the user their preference, if we're looking for
6131                            // an "always" type entry.
6132                            if (always && !pa.mPref.sameSet(query)) {
6133                                if (pa.mPref.isSuperset(query)) {
6134                                    // some components of the set are no longer present in
6135                                    // the query, but the preferred activity can still be reused
6136                                    if (DEBUG_PREFERRED) {
6137                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6138                                                + " still valid as only non-preferred components"
6139                                                + " were removed for " + intent + " type "
6140                                                + resolvedType);
6141                                    }
6142                                    // remove obsolete components and re-add the up-to-date filter
6143                                    PreferredActivity freshPa = new PreferredActivity(pa,
6144                                            pa.mPref.mMatch,
6145                                            pa.mPref.discardObsoleteComponents(query),
6146                                            pa.mPref.mComponent,
6147                                            pa.mPref.mAlways);
6148                                    pir.removeFilter(pa);
6149                                    pir.addFilter(freshPa);
6150                                    changed = true;
6151                                } else {
6152                                    Slog.i(TAG,
6153                                            "Result set changed, dropping preferred activity for "
6154                                                    + intent + " type " + resolvedType);
6155                                    if (DEBUG_PREFERRED) {
6156                                        Slog.v(TAG, "Removing preferred activity since set changed "
6157                                                + pa.mPref.mComponent);
6158                                    }
6159                                    pir.removeFilter(pa);
6160                                    // Re-add the filter as a "last chosen" entry (!always)
6161                                    PreferredActivity lastChosen = new PreferredActivity(
6162                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6163                                    pir.addFilter(lastChosen);
6164                                    changed = true;
6165                                    return null;
6166                                }
6167                            }
6168
6169                            // Yay! Either the set matched or we're looking for the last chosen
6170                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6171                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6172                            return ri;
6173                        }
6174                    }
6175                } finally {
6176                    if (changed) {
6177                        if (DEBUG_PREFERRED) {
6178                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6179                        }
6180                        scheduleWritePackageRestrictionsLocked(userId);
6181                    }
6182                }
6183            }
6184        }
6185        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6186        return null;
6187    }
6188
6189    /*
6190     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6191     */
6192    @Override
6193    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6194            int targetUserId) {
6195        mContext.enforceCallingOrSelfPermission(
6196                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6197        List<CrossProfileIntentFilter> matches =
6198                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6199        if (matches != null) {
6200            int size = matches.size();
6201            for (int i = 0; i < size; i++) {
6202                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6203            }
6204        }
6205        if (hasWebURI(intent)) {
6206            // cross-profile app linking works only towards the parent.
6207            final int callingUid = Binder.getCallingUid();
6208            final UserInfo parent = getProfileParent(sourceUserId);
6209            synchronized(mPackages) {
6210                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6211                        false /*includeInstantApps*/);
6212                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6213                        intent, resolvedType, flags, sourceUserId, parent.id);
6214                return xpDomainInfo != null;
6215            }
6216        }
6217        return false;
6218    }
6219
6220    private UserInfo getProfileParent(int userId) {
6221        final long identity = Binder.clearCallingIdentity();
6222        try {
6223            return sUserManager.getProfileParent(userId);
6224        } finally {
6225            Binder.restoreCallingIdentity(identity);
6226        }
6227    }
6228
6229    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6230            String resolvedType, int userId) {
6231        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6232        if (resolver != null) {
6233            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6234        }
6235        return null;
6236    }
6237
6238    @Override
6239    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6240            String resolvedType, int flags, int userId) {
6241        try {
6242            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6243
6244            return new ParceledListSlice<>(
6245                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6246        } finally {
6247            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6248        }
6249    }
6250
6251    /**
6252     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6253     * instant, returns {@code null}.
6254     */
6255    private String getInstantAppPackageName(int callingUid) {
6256        synchronized (mPackages) {
6257            // If the caller is an isolated app use the owner's uid for the lookup.
6258            if (Process.isIsolated(callingUid)) {
6259                callingUid = mIsolatedOwners.get(callingUid);
6260            }
6261            final int appId = UserHandle.getAppId(callingUid);
6262            final Object obj = mSettings.getUserIdLPr(appId);
6263            if (obj instanceof PackageSetting) {
6264                final PackageSetting ps = (PackageSetting) obj;
6265                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6266                return isInstantApp ? ps.pkg.packageName : null;
6267            }
6268        }
6269        return null;
6270    }
6271
6272    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6273            String resolvedType, int flags, int userId) {
6274        return queryIntentActivitiesInternal(
6275                intent, resolvedType, flags, Binder.getCallingUid(), userId,
6276                false /*resolveForStart*/, true /*allowDynamicSplits*/);
6277    }
6278
6279    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6280            String resolvedType, int flags, int filterCallingUid, int userId,
6281            boolean resolveForStart, boolean allowDynamicSplits) {
6282        if (!sUserManager.exists(userId)) return Collections.emptyList();
6283        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6284        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6285                false /* requireFullPermission */, false /* checkShell */,
6286                "query intent activities");
6287        final String pkgName = intent.getPackage();
6288        ComponentName comp = intent.getComponent();
6289        if (comp == null) {
6290            if (intent.getSelector() != null) {
6291                intent = intent.getSelector();
6292                comp = intent.getComponent();
6293            }
6294        }
6295
6296        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6297                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6298        if (comp != null) {
6299            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6300            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6301            if (ai != null) {
6302                // When specifying an explicit component, we prevent the activity from being
6303                // used when either 1) the calling package is normal and the activity is within
6304                // an ephemeral application or 2) the calling package is ephemeral and the
6305                // activity is not visible to ephemeral applications.
6306                final boolean matchInstantApp =
6307                        (flags & PackageManager.MATCH_INSTANT) != 0;
6308                final boolean matchVisibleToInstantAppOnly =
6309                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6310                final boolean matchExplicitlyVisibleOnly =
6311                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6312                final boolean isCallerInstantApp =
6313                        instantAppPkgName != null;
6314                final boolean isTargetSameInstantApp =
6315                        comp.getPackageName().equals(instantAppPkgName);
6316                final boolean isTargetInstantApp =
6317                        (ai.applicationInfo.privateFlags
6318                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6319                final boolean isTargetVisibleToInstantApp =
6320                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6321                final boolean isTargetExplicitlyVisibleToInstantApp =
6322                        isTargetVisibleToInstantApp
6323                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6324                final boolean isTargetHiddenFromInstantApp =
6325                        !isTargetVisibleToInstantApp
6326                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6327                final boolean blockResolution =
6328                        !isTargetSameInstantApp
6329                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6330                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6331                                        && isTargetHiddenFromInstantApp));
6332                if (!blockResolution) {
6333                    final ResolveInfo ri = new ResolveInfo();
6334                    ri.activityInfo = ai;
6335                    list.add(ri);
6336                }
6337            }
6338            return applyPostResolutionFilter(
6339                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6340        }
6341
6342        // reader
6343        boolean sortResult = false;
6344        boolean addEphemeral = false;
6345        List<ResolveInfo> result;
6346        final boolean ephemeralDisabled = isEphemeralDisabled();
6347        synchronized (mPackages) {
6348            if (pkgName == null) {
6349                List<CrossProfileIntentFilter> matchingFilters =
6350                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6351                // Check for results that need to skip the current profile.
6352                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6353                        resolvedType, flags, userId);
6354                if (xpResolveInfo != null) {
6355                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6356                    xpResult.add(xpResolveInfo);
6357                    return applyPostResolutionFilter(
6358                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6359                            allowDynamicSplits, filterCallingUid, userId);
6360                }
6361
6362                // Check for results in the current profile.
6363                result = filterIfNotSystemUser(mActivities.queryIntent(
6364                        intent, resolvedType, flags, userId), userId);
6365                addEphemeral = !ephemeralDisabled
6366                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6367                // Check for cross profile results.
6368                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6369                xpResolveInfo = queryCrossProfileIntents(
6370                        matchingFilters, intent, resolvedType, flags, userId,
6371                        hasNonNegativePriorityResult);
6372                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6373                    boolean isVisibleToUser = filterIfNotSystemUser(
6374                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6375                    if (isVisibleToUser) {
6376                        result.add(xpResolveInfo);
6377                        sortResult = true;
6378                    }
6379                }
6380                if (hasWebURI(intent)) {
6381                    CrossProfileDomainInfo xpDomainInfo = null;
6382                    final UserInfo parent = getProfileParent(userId);
6383                    if (parent != null) {
6384                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6385                                flags, userId, parent.id);
6386                    }
6387                    if (xpDomainInfo != null) {
6388                        if (xpResolveInfo != null) {
6389                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6390                            // in the result.
6391                            result.remove(xpResolveInfo);
6392                        }
6393                        if (result.size() == 0 && !addEphemeral) {
6394                            // No result in current profile, but found candidate in parent user.
6395                            // And we are not going to add emphemeral app, so we can return the
6396                            // result straight away.
6397                            result.add(xpDomainInfo.resolveInfo);
6398                            return applyPostResolutionFilter(result, instantAppPkgName,
6399                                    allowDynamicSplits, filterCallingUid, userId);
6400                        }
6401                    } else if (result.size() <= 1 && !addEphemeral) {
6402                        // No result in parent user and <= 1 result in current profile, and we
6403                        // are not going to add emphemeral app, so we can return the result without
6404                        // further processing.
6405                        return applyPostResolutionFilter(result, instantAppPkgName,
6406                                allowDynamicSplits, filterCallingUid, userId);
6407                    }
6408                    // We have more than one candidate (combining results from current and parent
6409                    // profile), so we need filtering and sorting.
6410                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6411                            intent, flags, result, xpDomainInfo, userId);
6412                    sortResult = true;
6413                }
6414            } else {
6415                final PackageParser.Package pkg = mPackages.get(pkgName);
6416                result = null;
6417                if (pkg != null) {
6418                    result = filterIfNotSystemUser(
6419                            mActivities.queryIntentForPackage(
6420                                    intent, resolvedType, flags, pkg.activities, userId),
6421                            userId);
6422                }
6423                if (result == null || result.size() == 0) {
6424                    // the caller wants to resolve for a particular package; however, there
6425                    // were no installed results, so, try to find an ephemeral result
6426                    addEphemeral = !ephemeralDisabled
6427                            && isInstantAppAllowed(
6428                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6429                    if (result == null) {
6430                        result = new ArrayList<>();
6431                    }
6432                }
6433            }
6434        }
6435        if (addEphemeral) {
6436            result = maybeAddInstantAppInstaller(
6437                    result, intent, resolvedType, flags, userId, resolveForStart);
6438        }
6439        if (sortResult) {
6440            Collections.sort(result, mResolvePrioritySorter);
6441        }
6442        return applyPostResolutionFilter(
6443                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6444    }
6445
6446    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6447            String resolvedType, int flags, int userId, boolean resolveForStart) {
6448        // first, check to see if we've got an instant app already installed
6449        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6450        ResolveInfo localInstantApp = null;
6451        boolean blockResolution = false;
6452        if (!alreadyResolvedLocally) {
6453            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6454                    flags
6455                        | PackageManager.GET_RESOLVED_FILTER
6456                        | PackageManager.MATCH_INSTANT
6457                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6458                    userId);
6459            for (int i = instantApps.size() - 1; i >= 0; --i) {
6460                final ResolveInfo info = instantApps.get(i);
6461                final String packageName = info.activityInfo.packageName;
6462                final PackageSetting ps = mSettings.mPackages.get(packageName);
6463                if (ps.getInstantApp(userId)) {
6464                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6465                    final int status = (int)(packedStatus >> 32);
6466                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6467                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6468                        // there's a local instant application installed, but, the user has
6469                        // chosen to never use it; skip resolution and don't acknowledge
6470                        // an instant application is even available
6471                        if (DEBUG_EPHEMERAL) {
6472                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6473                        }
6474                        blockResolution = true;
6475                        break;
6476                    } else {
6477                        // we have a locally installed instant application; skip resolution
6478                        // but acknowledge there's an instant application available
6479                        if (DEBUG_EPHEMERAL) {
6480                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6481                        }
6482                        localInstantApp = info;
6483                        break;
6484                    }
6485                }
6486            }
6487        }
6488        // no app installed, let's see if one's available
6489        AuxiliaryResolveInfo auxiliaryResponse = null;
6490        if (!blockResolution) {
6491            if (localInstantApp == null) {
6492                // we don't have an instant app locally, resolve externally
6493                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6494                final InstantAppRequest requestObject = new InstantAppRequest(
6495                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6496                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6497                        resolveForStart);
6498                auxiliaryResponse =
6499                        InstantAppResolver.doInstantAppResolutionPhaseOne(
6500                                mContext, mInstantAppResolverConnection, requestObject);
6501                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6502            } else {
6503                // we have an instant application locally, but, we can't admit that since
6504                // callers shouldn't be able to determine prior browsing. create a dummy
6505                // auxiliary response so the downstream code behaves as if there's an
6506                // instant application available externally. when it comes time to start
6507                // the instant application, we'll do the right thing.
6508                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6509                auxiliaryResponse = new AuxiliaryResolveInfo(
6510                        ai.packageName, null /*splitName*/, null /*failureActivity*/,
6511                        ai.versionCode, null /*failureIntent*/);
6512            }
6513        }
6514        if (auxiliaryResponse != null) {
6515            if (DEBUG_EPHEMERAL) {
6516                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6517            }
6518            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6519            final PackageSetting ps =
6520                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6521            if (ps != null) {
6522                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6523                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6524                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
6525                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6526                // make sure this resolver is the default
6527                ephemeralInstaller.isDefault = true;
6528                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6529                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6530                // add a non-generic filter
6531                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6532                ephemeralInstaller.filter.addDataPath(
6533                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6534                ephemeralInstaller.isInstantAppAvailable = true;
6535                result.add(ephemeralInstaller);
6536            }
6537        }
6538        return result;
6539    }
6540
6541    private static class CrossProfileDomainInfo {
6542        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6543        ResolveInfo resolveInfo;
6544        /* Best domain verification status of the activities found in the other profile */
6545        int bestDomainVerificationStatus;
6546    }
6547
6548    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6549            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6550        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6551                sourceUserId)) {
6552            return null;
6553        }
6554        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6555                resolvedType, flags, parentUserId);
6556
6557        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6558            return null;
6559        }
6560        CrossProfileDomainInfo result = null;
6561        int size = resultTargetUser.size();
6562        for (int i = 0; i < size; i++) {
6563            ResolveInfo riTargetUser = resultTargetUser.get(i);
6564            // Intent filter verification is only for filters that specify a host. So don't return
6565            // those that handle all web uris.
6566            if (riTargetUser.handleAllWebDataURI) {
6567                continue;
6568            }
6569            String packageName = riTargetUser.activityInfo.packageName;
6570            PackageSetting ps = mSettings.mPackages.get(packageName);
6571            if (ps == null) {
6572                continue;
6573            }
6574            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6575            int status = (int)(verificationState >> 32);
6576            if (result == null) {
6577                result = new CrossProfileDomainInfo();
6578                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6579                        sourceUserId, parentUserId);
6580                result.bestDomainVerificationStatus = status;
6581            } else {
6582                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6583                        result.bestDomainVerificationStatus);
6584            }
6585        }
6586        // Don't consider matches with status NEVER across profiles.
6587        if (result != null && result.bestDomainVerificationStatus
6588                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6589            return null;
6590        }
6591        return result;
6592    }
6593
6594    /**
6595     * Verification statuses are ordered from the worse to the best, except for
6596     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6597     */
6598    private int bestDomainVerificationStatus(int status1, int status2) {
6599        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6600            return status2;
6601        }
6602        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6603            return status1;
6604        }
6605        return (int) MathUtils.max(status1, status2);
6606    }
6607
6608    private boolean isUserEnabled(int userId) {
6609        long callingId = Binder.clearCallingIdentity();
6610        try {
6611            UserInfo userInfo = sUserManager.getUserInfo(userId);
6612            return userInfo != null && userInfo.isEnabled();
6613        } finally {
6614            Binder.restoreCallingIdentity(callingId);
6615        }
6616    }
6617
6618    /**
6619     * Filter out activities with systemUserOnly flag set, when current user is not System.
6620     *
6621     * @return filtered list
6622     */
6623    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6624        if (userId == UserHandle.USER_SYSTEM) {
6625            return resolveInfos;
6626        }
6627        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6628            ResolveInfo info = resolveInfos.get(i);
6629            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6630                resolveInfos.remove(i);
6631            }
6632        }
6633        return resolveInfos;
6634    }
6635
6636    /**
6637     * Filters out ephemeral activities.
6638     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6639     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6640     *
6641     * @param resolveInfos The pre-filtered list of resolved activities
6642     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6643     *          is performed.
6644     * @return A filtered list of resolved activities.
6645     */
6646    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6647            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) {
6648        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6649            final ResolveInfo info = resolveInfos.get(i);
6650            // allow activities that are defined in the provided package
6651            if (allowDynamicSplits
6652                    && info.activityInfo.splitName != null
6653                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6654                            info.activityInfo.splitName)) {
6655                if (mInstantAppInstallerInfo == null) {
6656                    if (DEBUG_INSTALL) {
6657                        Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
6658                    }
6659                    resolveInfos.remove(i);
6660                    continue;
6661                }
6662                // requested activity is defined in a split that hasn't been installed yet.
6663                // add the installer to the resolve list
6664                if (DEBUG_INSTALL) {
6665                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6666                }
6667                final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
6668                final ComponentName installFailureActivity = findInstallFailureActivity(
6669                        info.activityInfo.packageName,  filterCallingUid, userId);
6670                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6671                        info.activityInfo.packageName, info.activityInfo.splitName,
6672                        installFailureActivity,
6673                        info.activityInfo.applicationInfo.versionCode,
6674                        null /*failureIntent*/);
6675                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6676                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6677                // add a non-generic filter
6678                installerInfo.filter = new IntentFilter();
6679
6680                // This resolve info may appear in the chooser UI, so let us make it
6681                // look as the one it replaces as far as the user is concerned which
6682                // requires loading the correct label and icon for the resolve info.
6683                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6684                installerInfo.labelRes = info.resolveLabelResId();
6685                installerInfo.icon = info.resolveIconResId();
6686
6687                // propagate priority/preferred order/default
6688                installerInfo.priority = info.priority;
6689                installerInfo.preferredOrder = info.preferredOrder;
6690                installerInfo.isDefault = info.isDefault;
6691                resolveInfos.set(i, installerInfo);
6692                continue;
6693            }
6694            // caller is a full app, don't need to apply any other filtering
6695            if (ephemeralPkgName == null) {
6696                continue;
6697            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
6698                // caller is same app; don't need to apply any other filtering
6699                continue;
6700            }
6701            // allow activities that have been explicitly exposed to ephemeral apps
6702            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6703            if (!isEphemeralApp
6704                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6705                continue;
6706            }
6707            resolveInfos.remove(i);
6708        }
6709        return resolveInfos;
6710    }
6711
6712    /**
6713     * Returns the activity component that can handle install failures.
6714     * <p>By default, the instant application installer handles failures. However, an
6715     * application may want to handle failures on its own. Applications do this by
6716     * creating an activity with an intent filter that handles the action
6717     * {@link Intent#ACTION_INSTALL_FAILURE}.
6718     */
6719    private @Nullable ComponentName findInstallFailureActivity(
6720            String packageName, int filterCallingUid, int userId) {
6721        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
6722        failureActivityIntent.setPackage(packageName);
6723        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
6724        final List<ResolveInfo> result = queryIntentActivitiesInternal(
6725                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
6726                false /*resolveForStart*/, false /*allowDynamicSplits*/);
6727        final int NR = result.size();
6728        if (NR > 0) {
6729            for (int i = 0; i < NR; i++) {
6730                final ResolveInfo info = result.get(i);
6731                if (info.activityInfo.splitName != null) {
6732                    continue;
6733                }
6734                return new ComponentName(packageName, info.activityInfo.name);
6735            }
6736        }
6737        return null;
6738    }
6739
6740    /**
6741     * @param resolveInfos list of resolve infos in descending priority order
6742     * @return if the list contains a resolve info with non-negative priority
6743     */
6744    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6745        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6746    }
6747
6748    private static boolean hasWebURI(Intent intent) {
6749        if (intent.getData() == null) {
6750            return false;
6751        }
6752        final String scheme = intent.getScheme();
6753        if (TextUtils.isEmpty(scheme)) {
6754            return false;
6755        }
6756        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6757    }
6758
6759    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6760            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6761            int userId) {
6762        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6763
6764        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6765            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6766                    candidates.size());
6767        }
6768
6769        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6770        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6771        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6772        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6773        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6774        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6775
6776        synchronized (mPackages) {
6777            final int count = candidates.size();
6778            // First, try to use linked apps. Partition the candidates into four lists:
6779            // one for the final results, one for the "do not use ever", one for "undefined status"
6780            // and finally one for "browser app type".
6781            for (int n=0; n<count; n++) {
6782                ResolveInfo info = candidates.get(n);
6783                String packageName = info.activityInfo.packageName;
6784                PackageSetting ps = mSettings.mPackages.get(packageName);
6785                if (ps != null) {
6786                    // Add to the special match all list (Browser use case)
6787                    if (info.handleAllWebDataURI) {
6788                        matchAllList.add(info);
6789                        continue;
6790                    }
6791                    // Try to get the status from User settings first
6792                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6793                    int status = (int)(packedStatus >> 32);
6794                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6795                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6796                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6797                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6798                                    + " : linkgen=" + linkGeneration);
6799                        }
6800                        // Use link-enabled generation as preferredOrder, i.e.
6801                        // prefer newly-enabled over earlier-enabled.
6802                        info.preferredOrder = linkGeneration;
6803                        alwaysList.add(info);
6804                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6805                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6806                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6807                        }
6808                        neverList.add(info);
6809                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6810                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6811                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6812                        }
6813                        alwaysAskList.add(info);
6814                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6815                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6816                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6817                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6818                        }
6819                        undefinedList.add(info);
6820                    }
6821                }
6822            }
6823
6824            // We'll want to include browser possibilities in a few cases
6825            boolean includeBrowser = false;
6826
6827            // First try to add the "always" resolution(s) for the current user, if any
6828            if (alwaysList.size() > 0) {
6829                result.addAll(alwaysList);
6830            } else {
6831                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6832                result.addAll(undefinedList);
6833                // Maybe add one for the other profile.
6834                if (xpDomainInfo != null && (
6835                        xpDomainInfo.bestDomainVerificationStatus
6836                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6837                    result.add(xpDomainInfo.resolveInfo);
6838                }
6839                includeBrowser = true;
6840            }
6841
6842            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6843            // If there were 'always' entries their preferred order has been set, so we also
6844            // back that off to make the alternatives equivalent
6845            if (alwaysAskList.size() > 0) {
6846                for (ResolveInfo i : result) {
6847                    i.preferredOrder = 0;
6848                }
6849                result.addAll(alwaysAskList);
6850                includeBrowser = true;
6851            }
6852
6853            if (includeBrowser) {
6854                // Also add browsers (all of them or only the default one)
6855                if (DEBUG_DOMAIN_VERIFICATION) {
6856                    Slog.v(TAG, "   ...including browsers in candidate set");
6857                }
6858                if ((matchFlags & MATCH_ALL) != 0) {
6859                    result.addAll(matchAllList);
6860                } else {
6861                    // Browser/generic handling case.  If there's a default browser, go straight
6862                    // to that (but only if there is no other higher-priority match).
6863                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6864                    int maxMatchPrio = 0;
6865                    ResolveInfo defaultBrowserMatch = null;
6866                    final int numCandidates = matchAllList.size();
6867                    for (int n = 0; n < numCandidates; n++) {
6868                        ResolveInfo info = matchAllList.get(n);
6869                        // track the highest overall match priority...
6870                        if (info.priority > maxMatchPrio) {
6871                            maxMatchPrio = info.priority;
6872                        }
6873                        // ...and the highest-priority default browser match
6874                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6875                            if (defaultBrowserMatch == null
6876                                    || (defaultBrowserMatch.priority < info.priority)) {
6877                                if (debug) {
6878                                    Slog.v(TAG, "Considering default browser match " + info);
6879                                }
6880                                defaultBrowserMatch = info;
6881                            }
6882                        }
6883                    }
6884                    if (defaultBrowserMatch != null
6885                            && defaultBrowserMatch.priority >= maxMatchPrio
6886                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6887                    {
6888                        if (debug) {
6889                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6890                        }
6891                        result.add(defaultBrowserMatch);
6892                    } else {
6893                        result.addAll(matchAllList);
6894                    }
6895                }
6896
6897                // If there is nothing selected, add all candidates and remove the ones that the user
6898                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6899                if (result.size() == 0) {
6900                    result.addAll(candidates);
6901                    result.removeAll(neverList);
6902                }
6903            }
6904        }
6905        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6906            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6907                    result.size());
6908            for (ResolveInfo info : result) {
6909                Slog.v(TAG, "  + " + info.activityInfo);
6910            }
6911        }
6912        return result;
6913    }
6914
6915    // Returns a packed value as a long:
6916    //
6917    // high 'int'-sized word: link status: undefined/ask/never/always.
6918    // low 'int'-sized word: relative priority among 'always' results.
6919    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6920        long result = ps.getDomainVerificationStatusForUser(userId);
6921        // if none available, get the master status
6922        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6923            if (ps.getIntentFilterVerificationInfo() != null) {
6924                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6925            }
6926        }
6927        return result;
6928    }
6929
6930    private ResolveInfo querySkipCurrentProfileIntents(
6931            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6932            int flags, int sourceUserId) {
6933        if (matchingFilters != null) {
6934            int size = matchingFilters.size();
6935            for (int i = 0; i < size; i ++) {
6936                CrossProfileIntentFilter filter = matchingFilters.get(i);
6937                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6938                    // Checking if there are activities in the target user that can handle the
6939                    // intent.
6940                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6941                            resolvedType, flags, sourceUserId);
6942                    if (resolveInfo != null) {
6943                        return resolveInfo;
6944                    }
6945                }
6946            }
6947        }
6948        return null;
6949    }
6950
6951    // Return matching ResolveInfo in target user if any.
6952    private ResolveInfo queryCrossProfileIntents(
6953            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6954            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6955        if (matchingFilters != null) {
6956            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6957            // match the same intent. For performance reasons, it is better not to
6958            // run queryIntent twice for the same userId
6959            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6960            int size = matchingFilters.size();
6961            for (int i = 0; i < size; i++) {
6962                CrossProfileIntentFilter filter = matchingFilters.get(i);
6963                int targetUserId = filter.getTargetUserId();
6964                boolean skipCurrentProfile =
6965                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6966                boolean skipCurrentProfileIfNoMatchFound =
6967                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6968                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6969                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6970                    // Checking if there are activities in the target user that can handle the
6971                    // intent.
6972                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6973                            resolvedType, flags, sourceUserId);
6974                    if (resolveInfo != null) return resolveInfo;
6975                    alreadyTriedUserIds.put(targetUserId, true);
6976                }
6977            }
6978        }
6979        return null;
6980    }
6981
6982    /**
6983     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6984     * will forward the intent to the filter's target user.
6985     * Otherwise, returns null.
6986     */
6987    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6988            String resolvedType, int flags, int sourceUserId) {
6989        int targetUserId = filter.getTargetUserId();
6990        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6991                resolvedType, flags, targetUserId);
6992        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6993            // If all the matches in the target profile are suspended, return null.
6994            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6995                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6996                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6997                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6998                            targetUserId);
6999                }
7000            }
7001        }
7002        return null;
7003    }
7004
7005    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7006            int sourceUserId, int targetUserId) {
7007        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7008        long ident = Binder.clearCallingIdentity();
7009        boolean targetIsProfile;
7010        try {
7011            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7012        } finally {
7013            Binder.restoreCallingIdentity(ident);
7014        }
7015        String className;
7016        if (targetIsProfile) {
7017            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7018        } else {
7019            className = FORWARD_INTENT_TO_PARENT;
7020        }
7021        ComponentName forwardingActivityComponentName = new ComponentName(
7022                mAndroidApplication.packageName, className);
7023        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7024                sourceUserId);
7025        if (!targetIsProfile) {
7026            forwardingActivityInfo.showUserIcon = targetUserId;
7027            forwardingResolveInfo.noResourceId = true;
7028        }
7029        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7030        forwardingResolveInfo.priority = 0;
7031        forwardingResolveInfo.preferredOrder = 0;
7032        forwardingResolveInfo.match = 0;
7033        forwardingResolveInfo.isDefault = true;
7034        forwardingResolveInfo.filter = filter;
7035        forwardingResolveInfo.targetUserId = targetUserId;
7036        return forwardingResolveInfo;
7037    }
7038
7039    @Override
7040    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7041            Intent[] specifics, String[] specificTypes, Intent intent,
7042            String resolvedType, int flags, int userId) {
7043        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7044                specificTypes, intent, resolvedType, flags, userId));
7045    }
7046
7047    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7048            Intent[] specifics, String[] specificTypes, Intent intent,
7049            String resolvedType, int flags, int userId) {
7050        if (!sUserManager.exists(userId)) return Collections.emptyList();
7051        final int callingUid = Binder.getCallingUid();
7052        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7053                false /*includeInstantApps*/);
7054        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7055                false /*requireFullPermission*/, false /*checkShell*/,
7056                "query intent activity options");
7057        final String resultsAction = intent.getAction();
7058
7059        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7060                | PackageManager.GET_RESOLVED_FILTER, userId);
7061
7062        if (DEBUG_INTENT_MATCHING) {
7063            Log.v(TAG, "Query " + intent + ": " + results);
7064        }
7065
7066        int specificsPos = 0;
7067        int N;
7068
7069        // todo: note that the algorithm used here is O(N^2).  This
7070        // isn't a problem in our current environment, but if we start running
7071        // into situations where we have more than 5 or 10 matches then this
7072        // should probably be changed to something smarter...
7073
7074        // First we go through and resolve each of the specific items
7075        // that were supplied, taking care of removing any corresponding
7076        // duplicate items in the generic resolve list.
7077        if (specifics != null) {
7078            for (int i=0; i<specifics.length; i++) {
7079                final Intent sintent = specifics[i];
7080                if (sintent == null) {
7081                    continue;
7082                }
7083
7084                if (DEBUG_INTENT_MATCHING) {
7085                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7086                }
7087
7088                String action = sintent.getAction();
7089                if (resultsAction != null && resultsAction.equals(action)) {
7090                    // If this action was explicitly requested, then don't
7091                    // remove things that have it.
7092                    action = null;
7093                }
7094
7095                ResolveInfo ri = null;
7096                ActivityInfo ai = null;
7097
7098                ComponentName comp = sintent.getComponent();
7099                if (comp == null) {
7100                    ri = resolveIntent(
7101                        sintent,
7102                        specificTypes != null ? specificTypes[i] : null,
7103                            flags, userId);
7104                    if (ri == null) {
7105                        continue;
7106                    }
7107                    if (ri == mResolveInfo) {
7108                        // ACK!  Must do something better with this.
7109                    }
7110                    ai = ri.activityInfo;
7111                    comp = new ComponentName(ai.applicationInfo.packageName,
7112                            ai.name);
7113                } else {
7114                    ai = getActivityInfo(comp, flags, userId);
7115                    if (ai == null) {
7116                        continue;
7117                    }
7118                }
7119
7120                // Look for any generic query activities that are duplicates
7121                // of this specific one, and remove them from the results.
7122                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7123                N = results.size();
7124                int j;
7125                for (j=specificsPos; j<N; j++) {
7126                    ResolveInfo sri = results.get(j);
7127                    if ((sri.activityInfo.name.equals(comp.getClassName())
7128                            && sri.activityInfo.applicationInfo.packageName.equals(
7129                                    comp.getPackageName()))
7130                        || (action != null && sri.filter.matchAction(action))) {
7131                        results.remove(j);
7132                        if (DEBUG_INTENT_MATCHING) Log.v(
7133                            TAG, "Removing duplicate item from " + j
7134                            + " due to specific " + specificsPos);
7135                        if (ri == null) {
7136                            ri = sri;
7137                        }
7138                        j--;
7139                        N--;
7140                    }
7141                }
7142
7143                // Add this specific item to its proper place.
7144                if (ri == null) {
7145                    ri = new ResolveInfo();
7146                    ri.activityInfo = ai;
7147                }
7148                results.add(specificsPos, ri);
7149                ri.specificIndex = i;
7150                specificsPos++;
7151            }
7152        }
7153
7154        // Now we go through the remaining generic results and remove any
7155        // duplicate actions that are found here.
7156        N = results.size();
7157        for (int i=specificsPos; i<N-1; i++) {
7158            final ResolveInfo rii = results.get(i);
7159            if (rii.filter == null) {
7160                continue;
7161            }
7162
7163            // Iterate over all of the actions of this result's intent
7164            // filter...  typically this should be just one.
7165            final Iterator<String> it = rii.filter.actionsIterator();
7166            if (it == null) {
7167                continue;
7168            }
7169            while (it.hasNext()) {
7170                final String action = it.next();
7171                if (resultsAction != null && resultsAction.equals(action)) {
7172                    // If this action was explicitly requested, then don't
7173                    // remove things that have it.
7174                    continue;
7175                }
7176                for (int j=i+1; j<N; j++) {
7177                    final ResolveInfo rij = results.get(j);
7178                    if (rij.filter != null && rij.filter.hasAction(action)) {
7179                        results.remove(j);
7180                        if (DEBUG_INTENT_MATCHING) Log.v(
7181                            TAG, "Removing duplicate item from " + j
7182                            + " due to action " + action + " at " + i);
7183                        j--;
7184                        N--;
7185                    }
7186                }
7187            }
7188
7189            // If the caller didn't request filter information, drop it now
7190            // so we don't have to marshall/unmarshall it.
7191            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7192                rii.filter = null;
7193            }
7194        }
7195
7196        // Filter out the caller activity if so requested.
7197        if (caller != null) {
7198            N = results.size();
7199            for (int i=0; i<N; i++) {
7200                ActivityInfo ainfo = results.get(i).activityInfo;
7201                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7202                        && caller.getClassName().equals(ainfo.name)) {
7203                    results.remove(i);
7204                    break;
7205                }
7206            }
7207        }
7208
7209        // If the caller didn't request filter information,
7210        // drop them now so we don't have to
7211        // marshall/unmarshall it.
7212        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7213            N = results.size();
7214            for (int i=0; i<N; i++) {
7215                results.get(i).filter = null;
7216            }
7217        }
7218
7219        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7220        return results;
7221    }
7222
7223    @Override
7224    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7225            String resolvedType, int flags, int userId) {
7226        return new ParceledListSlice<>(
7227                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7228                        false /*allowDynamicSplits*/));
7229    }
7230
7231    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7232            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7233        if (!sUserManager.exists(userId)) return Collections.emptyList();
7234        final int callingUid = Binder.getCallingUid();
7235        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7236                false /*requireFullPermission*/, false /*checkShell*/,
7237                "query intent receivers");
7238        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7239        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7240                false /*includeInstantApps*/);
7241        ComponentName comp = intent.getComponent();
7242        if (comp == null) {
7243            if (intent.getSelector() != null) {
7244                intent = intent.getSelector();
7245                comp = intent.getComponent();
7246            }
7247        }
7248        if (comp != null) {
7249            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7250            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7251            if (ai != null) {
7252                // When specifying an explicit component, we prevent the activity from being
7253                // used when either 1) the calling package is normal and the activity is within
7254                // an instant application or 2) the calling package is ephemeral and the
7255                // activity is not visible to instant applications.
7256                final boolean matchInstantApp =
7257                        (flags & PackageManager.MATCH_INSTANT) != 0;
7258                final boolean matchVisibleToInstantAppOnly =
7259                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7260                final boolean matchExplicitlyVisibleOnly =
7261                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7262                final boolean isCallerInstantApp =
7263                        instantAppPkgName != null;
7264                final boolean isTargetSameInstantApp =
7265                        comp.getPackageName().equals(instantAppPkgName);
7266                final boolean isTargetInstantApp =
7267                        (ai.applicationInfo.privateFlags
7268                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7269                final boolean isTargetVisibleToInstantApp =
7270                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7271                final boolean isTargetExplicitlyVisibleToInstantApp =
7272                        isTargetVisibleToInstantApp
7273                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7274                final boolean isTargetHiddenFromInstantApp =
7275                        !isTargetVisibleToInstantApp
7276                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7277                final boolean blockResolution =
7278                        !isTargetSameInstantApp
7279                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7280                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7281                                        && isTargetHiddenFromInstantApp));
7282                if (!blockResolution) {
7283                    ResolveInfo ri = new ResolveInfo();
7284                    ri.activityInfo = ai;
7285                    list.add(ri);
7286                }
7287            }
7288            return applyPostResolutionFilter(
7289                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7290        }
7291
7292        // reader
7293        synchronized (mPackages) {
7294            String pkgName = intent.getPackage();
7295            if (pkgName == null) {
7296                final List<ResolveInfo> result =
7297                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7298                return applyPostResolutionFilter(
7299                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7300            }
7301            final PackageParser.Package pkg = mPackages.get(pkgName);
7302            if (pkg != null) {
7303                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7304                        intent, resolvedType, flags, pkg.receivers, userId);
7305                return applyPostResolutionFilter(
7306                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7307            }
7308            return Collections.emptyList();
7309        }
7310    }
7311
7312    @Override
7313    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7314        final int callingUid = Binder.getCallingUid();
7315        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7316    }
7317
7318    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7319            int userId, int callingUid) {
7320        if (!sUserManager.exists(userId)) return null;
7321        flags = updateFlagsForResolve(
7322                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7323        List<ResolveInfo> query = queryIntentServicesInternal(
7324                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7325        if (query != null) {
7326            if (query.size() >= 1) {
7327                // If there is more than one service with the same priority,
7328                // just arbitrarily pick the first one.
7329                return query.get(0);
7330            }
7331        }
7332        return null;
7333    }
7334
7335    @Override
7336    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7337            String resolvedType, int flags, int userId) {
7338        final int callingUid = Binder.getCallingUid();
7339        return new ParceledListSlice<>(queryIntentServicesInternal(
7340                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7341    }
7342
7343    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7344            String resolvedType, int flags, int userId, int callingUid,
7345            boolean includeInstantApps) {
7346        if (!sUserManager.exists(userId)) return Collections.emptyList();
7347        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7348                false /*requireFullPermission*/, false /*checkShell*/,
7349                "query intent receivers");
7350        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7351        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7352        ComponentName comp = intent.getComponent();
7353        if (comp == null) {
7354            if (intent.getSelector() != null) {
7355                intent = intent.getSelector();
7356                comp = intent.getComponent();
7357            }
7358        }
7359        if (comp != null) {
7360            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7361            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7362            if (si != null) {
7363                // When specifying an explicit component, we prevent the service from being
7364                // used when either 1) the service is in an instant application and the
7365                // caller is not the same instant application or 2) the calling package is
7366                // ephemeral and the activity is not visible to ephemeral applications.
7367                final boolean matchInstantApp =
7368                        (flags & PackageManager.MATCH_INSTANT) != 0;
7369                final boolean matchVisibleToInstantAppOnly =
7370                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7371                final boolean isCallerInstantApp =
7372                        instantAppPkgName != null;
7373                final boolean isTargetSameInstantApp =
7374                        comp.getPackageName().equals(instantAppPkgName);
7375                final boolean isTargetInstantApp =
7376                        (si.applicationInfo.privateFlags
7377                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7378                final boolean isTargetHiddenFromInstantApp =
7379                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7380                final boolean blockResolution =
7381                        !isTargetSameInstantApp
7382                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7383                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7384                                        && isTargetHiddenFromInstantApp));
7385                if (!blockResolution) {
7386                    final ResolveInfo ri = new ResolveInfo();
7387                    ri.serviceInfo = si;
7388                    list.add(ri);
7389                }
7390            }
7391            return list;
7392        }
7393
7394        // reader
7395        synchronized (mPackages) {
7396            String pkgName = intent.getPackage();
7397            if (pkgName == null) {
7398                return applyPostServiceResolutionFilter(
7399                        mServices.queryIntent(intent, resolvedType, flags, userId),
7400                        instantAppPkgName);
7401            }
7402            final PackageParser.Package pkg = mPackages.get(pkgName);
7403            if (pkg != null) {
7404                return applyPostServiceResolutionFilter(
7405                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7406                                userId),
7407                        instantAppPkgName);
7408            }
7409            return Collections.emptyList();
7410        }
7411    }
7412
7413    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7414            String instantAppPkgName) {
7415        if (instantAppPkgName == null) {
7416            return resolveInfos;
7417        }
7418        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7419            final ResolveInfo info = resolveInfos.get(i);
7420            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7421            // allow services that are defined in the provided package
7422            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7423                if (info.serviceInfo.splitName != null
7424                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7425                                info.serviceInfo.splitName)) {
7426                    // requested service is defined in a split that hasn't been installed yet.
7427                    // add the installer to the resolve list
7428                    if (DEBUG_EPHEMERAL) {
7429                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7430                    }
7431                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7432                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7433                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7434                            null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode,
7435                            null /*failureIntent*/);
7436                    // make sure this resolver is the default
7437                    installerInfo.isDefault = true;
7438                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7439                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7440                    // add a non-generic filter
7441                    installerInfo.filter = new IntentFilter();
7442                    // load resources from the correct package
7443                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7444                    resolveInfos.set(i, installerInfo);
7445                }
7446                continue;
7447            }
7448            // allow services that have been explicitly exposed to ephemeral apps
7449            if (!isEphemeralApp
7450                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7451                continue;
7452            }
7453            resolveInfos.remove(i);
7454        }
7455        return resolveInfos;
7456    }
7457
7458    @Override
7459    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7460            String resolvedType, int flags, int userId) {
7461        return new ParceledListSlice<>(
7462                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7463    }
7464
7465    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7466            Intent intent, String resolvedType, int flags, int userId) {
7467        if (!sUserManager.exists(userId)) return Collections.emptyList();
7468        final int callingUid = Binder.getCallingUid();
7469        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7470        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7471                false /*includeInstantApps*/);
7472        ComponentName comp = intent.getComponent();
7473        if (comp == null) {
7474            if (intent.getSelector() != null) {
7475                intent = intent.getSelector();
7476                comp = intent.getComponent();
7477            }
7478        }
7479        if (comp != null) {
7480            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7481            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7482            if (pi != null) {
7483                // When specifying an explicit component, we prevent the provider from being
7484                // used when either 1) the provider is in an instant application and the
7485                // caller is not the same instant application or 2) the calling package is an
7486                // instant application and the provider is not visible to instant applications.
7487                final boolean matchInstantApp =
7488                        (flags & PackageManager.MATCH_INSTANT) != 0;
7489                final boolean matchVisibleToInstantAppOnly =
7490                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7491                final boolean isCallerInstantApp =
7492                        instantAppPkgName != null;
7493                final boolean isTargetSameInstantApp =
7494                        comp.getPackageName().equals(instantAppPkgName);
7495                final boolean isTargetInstantApp =
7496                        (pi.applicationInfo.privateFlags
7497                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7498                final boolean isTargetHiddenFromInstantApp =
7499                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7500                final boolean blockResolution =
7501                        !isTargetSameInstantApp
7502                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7503                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7504                                        && isTargetHiddenFromInstantApp));
7505                if (!blockResolution) {
7506                    final ResolveInfo ri = new ResolveInfo();
7507                    ri.providerInfo = pi;
7508                    list.add(ri);
7509                }
7510            }
7511            return list;
7512        }
7513
7514        // reader
7515        synchronized (mPackages) {
7516            String pkgName = intent.getPackage();
7517            if (pkgName == null) {
7518                return applyPostContentProviderResolutionFilter(
7519                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7520                        instantAppPkgName);
7521            }
7522            final PackageParser.Package pkg = mPackages.get(pkgName);
7523            if (pkg != null) {
7524                return applyPostContentProviderResolutionFilter(
7525                        mProviders.queryIntentForPackage(
7526                        intent, resolvedType, flags, pkg.providers, userId),
7527                        instantAppPkgName);
7528            }
7529            return Collections.emptyList();
7530        }
7531    }
7532
7533    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7534            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7535        if (instantAppPkgName == null) {
7536            return resolveInfos;
7537        }
7538        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7539            final ResolveInfo info = resolveInfos.get(i);
7540            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7541            // allow providers that are defined in the provided package
7542            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7543                if (info.providerInfo.splitName != null
7544                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7545                                info.providerInfo.splitName)) {
7546                    // requested provider is defined in a split that hasn't been installed yet.
7547                    // add the installer to the resolve list
7548                    if (DEBUG_EPHEMERAL) {
7549                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7550                    }
7551                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7552                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7553                            info.providerInfo.packageName, info.providerInfo.splitName,
7554                            null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode,
7555                            null /*failureIntent*/);
7556                    // make sure this resolver is the default
7557                    installerInfo.isDefault = true;
7558                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7559                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7560                    // add a non-generic filter
7561                    installerInfo.filter = new IntentFilter();
7562                    // load resources from the correct package
7563                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7564                    resolveInfos.set(i, installerInfo);
7565                }
7566                continue;
7567            }
7568            // allow providers that have been explicitly exposed to instant applications
7569            if (!isEphemeralApp
7570                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7571                continue;
7572            }
7573            resolveInfos.remove(i);
7574        }
7575        return resolveInfos;
7576    }
7577
7578    @Override
7579    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7580        final int callingUid = Binder.getCallingUid();
7581        if (getInstantAppPackageName(callingUid) != null) {
7582            return ParceledListSlice.emptyList();
7583        }
7584        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7585        flags = updateFlagsForPackage(flags, userId, null);
7586        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7587        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7588                true /* requireFullPermission */, false /* checkShell */,
7589                "get installed packages");
7590
7591        // writer
7592        synchronized (mPackages) {
7593            ArrayList<PackageInfo> list;
7594            if (listUninstalled) {
7595                list = new ArrayList<>(mSettings.mPackages.size());
7596                for (PackageSetting ps : mSettings.mPackages.values()) {
7597                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7598                        continue;
7599                    }
7600                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7601                        continue;
7602                    }
7603                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7604                    if (pi != null) {
7605                        list.add(pi);
7606                    }
7607                }
7608            } else {
7609                list = new ArrayList<>(mPackages.size());
7610                for (PackageParser.Package p : mPackages.values()) {
7611                    final PackageSetting ps = (PackageSetting) p.mExtras;
7612                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7613                        continue;
7614                    }
7615                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7616                        continue;
7617                    }
7618                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7619                            p.mExtras, flags, userId);
7620                    if (pi != null) {
7621                        list.add(pi);
7622                    }
7623                }
7624            }
7625
7626            return new ParceledListSlice<>(list);
7627        }
7628    }
7629
7630    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7631            String[] permissions, boolean[] tmp, int flags, int userId) {
7632        int numMatch = 0;
7633        final PermissionsState permissionsState = ps.getPermissionsState();
7634        for (int i=0; i<permissions.length; i++) {
7635            final String permission = permissions[i];
7636            if (permissionsState.hasPermission(permission, userId)) {
7637                tmp[i] = true;
7638                numMatch++;
7639            } else {
7640                tmp[i] = false;
7641            }
7642        }
7643        if (numMatch == 0) {
7644            return;
7645        }
7646        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7647
7648        // The above might return null in cases of uninstalled apps or install-state
7649        // skew across users/profiles.
7650        if (pi != null) {
7651            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7652                if (numMatch == permissions.length) {
7653                    pi.requestedPermissions = permissions;
7654                } else {
7655                    pi.requestedPermissions = new String[numMatch];
7656                    numMatch = 0;
7657                    for (int i=0; i<permissions.length; i++) {
7658                        if (tmp[i]) {
7659                            pi.requestedPermissions[numMatch] = permissions[i];
7660                            numMatch++;
7661                        }
7662                    }
7663                }
7664            }
7665            list.add(pi);
7666        }
7667    }
7668
7669    @Override
7670    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7671            String[] permissions, int flags, int userId) {
7672        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7673        flags = updateFlagsForPackage(flags, userId, permissions);
7674        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7675                true /* requireFullPermission */, false /* checkShell */,
7676                "get packages holding permissions");
7677        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7678
7679        // writer
7680        synchronized (mPackages) {
7681            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7682            boolean[] tmpBools = new boolean[permissions.length];
7683            if (listUninstalled) {
7684                for (PackageSetting ps : mSettings.mPackages.values()) {
7685                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7686                            userId);
7687                }
7688            } else {
7689                for (PackageParser.Package pkg : mPackages.values()) {
7690                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7691                    if (ps != null) {
7692                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7693                                userId);
7694                    }
7695                }
7696            }
7697
7698            return new ParceledListSlice<PackageInfo>(list);
7699        }
7700    }
7701
7702    @Override
7703    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7704        final int callingUid = Binder.getCallingUid();
7705        if (getInstantAppPackageName(callingUid) != null) {
7706            return ParceledListSlice.emptyList();
7707        }
7708        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7709        flags = updateFlagsForApplication(flags, userId, null);
7710        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7711
7712        // writer
7713        synchronized (mPackages) {
7714            ArrayList<ApplicationInfo> list;
7715            if (listUninstalled) {
7716                list = new ArrayList<>(mSettings.mPackages.size());
7717                for (PackageSetting ps : mSettings.mPackages.values()) {
7718                    ApplicationInfo ai;
7719                    int effectiveFlags = flags;
7720                    if (ps.isSystem()) {
7721                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7722                    }
7723                    if (ps.pkg != null) {
7724                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7725                            continue;
7726                        }
7727                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7728                            continue;
7729                        }
7730                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7731                                ps.readUserState(userId), userId);
7732                        if (ai != null) {
7733                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7734                        }
7735                    } else {
7736                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7737                        // and already converts to externally visible package name
7738                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7739                                callingUid, effectiveFlags, userId);
7740                    }
7741                    if (ai != null) {
7742                        list.add(ai);
7743                    }
7744                }
7745            } else {
7746                list = new ArrayList<>(mPackages.size());
7747                for (PackageParser.Package p : mPackages.values()) {
7748                    if (p.mExtras != null) {
7749                        PackageSetting ps = (PackageSetting) p.mExtras;
7750                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
7751                            continue;
7752                        }
7753                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7754                            continue;
7755                        }
7756                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7757                                ps.readUserState(userId), userId);
7758                        if (ai != null) {
7759                            ai.packageName = resolveExternalPackageNameLPr(p);
7760                            list.add(ai);
7761                        }
7762                    }
7763                }
7764            }
7765
7766            return new ParceledListSlice<>(list);
7767        }
7768    }
7769
7770    @Override
7771    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7772        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7773            return null;
7774        }
7775        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
7776            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7777                    "getEphemeralApplications");
7778        }
7779        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7780                true /* requireFullPermission */, false /* checkShell */,
7781                "getEphemeralApplications");
7782        synchronized (mPackages) {
7783            List<InstantAppInfo> instantApps = mInstantAppRegistry
7784                    .getInstantAppsLPr(userId);
7785            if (instantApps != null) {
7786                return new ParceledListSlice<>(instantApps);
7787            }
7788        }
7789        return null;
7790    }
7791
7792    @Override
7793    public boolean isInstantApp(String packageName, int userId) {
7794        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7795                true /* requireFullPermission */, false /* checkShell */,
7796                "isInstantApp");
7797        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7798            return false;
7799        }
7800
7801        synchronized (mPackages) {
7802            int callingUid = Binder.getCallingUid();
7803            if (Process.isIsolated(callingUid)) {
7804                callingUid = mIsolatedOwners.get(callingUid);
7805            }
7806            final PackageSetting ps = mSettings.mPackages.get(packageName);
7807            PackageParser.Package pkg = mPackages.get(packageName);
7808            final boolean returnAllowed =
7809                    ps != null
7810                    && (isCallerSameApp(packageName, callingUid)
7811                            || canViewInstantApps(callingUid, userId)
7812                            || mInstantAppRegistry.isInstantAccessGranted(
7813                                    userId, UserHandle.getAppId(callingUid), ps.appId));
7814            if (returnAllowed) {
7815                return ps.getInstantApp(userId);
7816            }
7817        }
7818        return false;
7819    }
7820
7821    @Override
7822    public byte[] getInstantAppCookie(String packageName, int userId) {
7823        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7824            return null;
7825        }
7826
7827        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7828                true /* requireFullPermission */, false /* checkShell */,
7829                "getInstantAppCookie");
7830        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7831            return null;
7832        }
7833        synchronized (mPackages) {
7834            return mInstantAppRegistry.getInstantAppCookieLPw(
7835                    packageName, userId);
7836        }
7837    }
7838
7839    @Override
7840    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
7841        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7842            return true;
7843        }
7844
7845        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7846                true /* requireFullPermission */, true /* checkShell */,
7847                "setInstantAppCookie");
7848        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7849            return false;
7850        }
7851        synchronized (mPackages) {
7852            return mInstantAppRegistry.setInstantAppCookieLPw(
7853                    packageName, cookie, userId);
7854        }
7855    }
7856
7857    @Override
7858    public Bitmap getInstantAppIcon(String packageName, int userId) {
7859        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7860            return null;
7861        }
7862
7863        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
7864            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7865                    "getInstantAppIcon");
7866        }
7867        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7868                true /* requireFullPermission */, false /* checkShell */,
7869                "getInstantAppIcon");
7870
7871        synchronized (mPackages) {
7872            return mInstantAppRegistry.getInstantAppIconLPw(
7873                    packageName, userId);
7874        }
7875    }
7876
7877    private boolean isCallerSameApp(String packageName, int uid) {
7878        PackageParser.Package pkg = mPackages.get(packageName);
7879        return pkg != null
7880                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
7881    }
7882
7883    @Override
7884    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7885        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
7886            return ParceledListSlice.emptyList();
7887        }
7888        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7889    }
7890
7891    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
7892        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
7893
7894        // reader
7895        synchronized (mPackages) {
7896            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
7897            final int userId = UserHandle.getCallingUserId();
7898            while (i.hasNext()) {
7899                final PackageParser.Package p = i.next();
7900                if (p.applicationInfo == null) continue;
7901
7902                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
7903                        && !p.applicationInfo.isDirectBootAware();
7904                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
7905                        && p.applicationInfo.isDirectBootAware();
7906
7907                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
7908                        && (!mSafeMode || isSystemApp(p))
7909                        && (matchesUnaware || matchesAware)) {
7910                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
7911                    if (ps != null) {
7912                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7913                                ps.readUserState(userId), userId);
7914                        if (ai != null) {
7915                            finalList.add(ai);
7916                        }
7917                    }
7918                }
7919            }
7920        }
7921
7922        return finalList;
7923    }
7924
7925    @Override
7926    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
7927        return resolveContentProviderInternal(name, flags, userId);
7928    }
7929
7930    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
7931        if (!sUserManager.exists(userId)) return null;
7932        flags = updateFlagsForComponent(flags, userId, name);
7933        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
7934        // reader
7935        synchronized (mPackages) {
7936            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
7937            PackageSetting ps = provider != null
7938                    ? mSettings.mPackages.get(provider.owner.packageName)
7939                    : null;
7940            if (ps != null) {
7941                final boolean isInstantApp = ps.getInstantApp(userId);
7942                // normal application; filter out instant application provider
7943                if (instantAppPkgName == null && isInstantApp) {
7944                    return null;
7945                }
7946                // instant application; filter out other instant applications
7947                if (instantAppPkgName != null
7948                        && isInstantApp
7949                        && !provider.owner.packageName.equals(instantAppPkgName)) {
7950                    return null;
7951                }
7952                // instant application; filter out non-exposed provider
7953                if (instantAppPkgName != null
7954                        && !isInstantApp
7955                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
7956                    return null;
7957                }
7958                // provider not enabled
7959                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
7960                    return null;
7961                }
7962                return PackageParser.generateProviderInfo(
7963                        provider, flags, ps.readUserState(userId), userId);
7964            }
7965            return null;
7966        }
7967    }
7968
7969    /**
7970     * @deprecated
7971     */
7972    @Deprecated
7973    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
7974        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
7975            return;
7976        }
7977        // reader
7978        synchronized (mPackages) {
7979            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
7980                    .entrySet().iterator();
7981            final int userId = UserHandle.getCallingUserId();
7982            while (i.hasNext()) {
7983                Map.Entry<String, PackageParser.Provider> entry = i.next();
7984                PackageParser.Provider p = entry.getValue();
7985                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7986
7987                if (ps != null && p.syncable
7988                        && (!mSafeMode || (p.info.applicationInfo.flags
7989                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
7990                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
7991                            ps.readUserState(userId), userId);
7992                    if (info != null) {
7993                        outNames.add(entry.getKey());
7994                        outInfo.add(info);
7995                    }
7996                }
7997            }
7998        }
7999    }
8000
8001    @Override
8002    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8003            int uid, int flags, String metaDataKey) {
8004        final int callingUid = Binder.getCallingUid();
8005        final int userId = processName != null ? UserHandle.getUserId(uid)
8006                : UserHandle.getCallingUserId();
8007        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8008        flags = updateFlagsForComponent(flags, userId, processName);
8009        ArrayList<ProviderInfo> finalList = null;
8010        // reader
8011        synchronized (mPackages) {
8012            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8013            while (i.hasNext()) {
8014                final PackageParser.Provider p = i.next();
8015                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8016                if (ps != null && p.info.authority != null
8017                        && (processName == null
8018                                || (p.info.processName.equals(processName)
8019                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8020                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8021
8022                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8023                    // parameter.
8024                    if (metaDataKey != null
8025                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8026                        continue;
8027                    }
8028                    final ComponentName component =
8029                            new ComponentName(p.info.packageName, p.info.name);
8030                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8031                        continue;
8032                    }
8033                    if (finalList == null) {
8034                        finalList = new ArrayList<ProviderInfo>(3);
8035                    }
8036                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8037                            ps.readUserState(userId), userId);
8038                    if (info != null) {
8039                        finalList.add(info);
8040                    }
8041                }
8042            }
8043        }
8044
8045        if (finalList != null) {
8046            Collections.sort(finalList, mProviderInitOrderSorter);
8047            return new ParceledListSlice<ProviderInfo>(finalList);
8048        }
8049
8050        return ParceledListSlice.emptyList();
8051    }
8052
8053    @Override
8054    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8055        // reader
8056        synchronized (mPackages) {
8057            final int callingUid = Binder.getCallingUid();
8058            final int callingUserId = UserHandle.getUserId(callingUid);
8059            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8060            if (ps == null) return null;
8061            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8062                return null;
8063            }
8064            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8065            return PackageParser.generateInstrumentationInfo(i, flags);
8066        }
8067    }
8068
8069    @Override
8070    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8071            String targetPackage, int flags) {
8072        final int callingUid = Binder.getCallingUid();
8073        final int callingUserId = UserHandle.getUserId(callingUid);
8074        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8075        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8076            return ParceledListSlice.emptyList();
8077        }
8078        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8079    }
8080
8081    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8082            int flags) {
8083        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8084
8085        // reader
8086        synchronized (mPackages) {
8087            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8088            while (i.hasNext()) {
8089                final PackageParser.Instrumentation p = i.next();
8090                if (targetPackage == null
8091                        || targetPackage.equals(p.info.targetPackage)) {
8092                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8093                            flags);
8094                    if (ii != null) {
8095                        finalList.add(ii);
8096                    }
8097                }
8098            }
8099        }
8100
8101        return finalList;
8102    }
8103
8104    private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) {
8105        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]");
8106        try {
8107            scanDirLI(scanDir, parseFlags, scanFlags, currentTime);
8108        } finally {
8109            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8110        }
8111    }
8112
8113    private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) {
8114        final File[] files = scanDir.listFiles();
8115        if (ArrayUtils.isEmpty(files)) {
8116            Log.d(TAG, "No files in app dir " + scanDir);
8117            return;
8118        }
8119
8120        if (DEBUG_PACKAGE_SCANNING) {
8121            Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags
8122                    + " flags=0x" + Integer.toHexString(parseFlags));
8123        }
8124        try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8125                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8126                mParallelPackageParserCallback)) {
8127            // Submit files for parsing in parallel
8128            int fileCount = 0;
8129            for (File file : files) {
8130                final boolean isPackage = (isApkFile(file) || file.isDirectory())
8131                        && !PackageInstallerService.isStageName(file.getName());
8132                if (!isPackage) {
8133                    // Ignore entries which are not packages
8134                    continue;
8135                }
8136                parallelPackageParser.submit(file, parseFlags);
8137                fileCount++;
8138            }
8139
8140            // Process results one by one
8141            for (; fileCount > 0; fileCount--) {
8142                ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8143                Throwable throwable = parseResult.throwable;
8144                int errorCode = PackageManager.INSTALL_SUCCEEDED;
8145
8146                if (throwable == null) {
8147                    // TODO(toddke): move lower in the scan chain
8148                    // Static shared libraries have synthetic package names
8149                    if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8150                        renameStaticSharedLibraryPackage(parseResult.pkg);
8151                    }
8152                    try {
8153                        if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8154                            scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags,
8155                                    currentTime, null);
8156                        }
8157                    } catch (PackageManagerException e) {
8158                        errorCode = e.error;
8159                        Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8160                    }
8161                } else if (throwable instanceof PackageParser.PackageParserException) {
8162                    PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8163                            throwable;
8164                    errorCode = e.error;
8165                    Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8166                } else {
8167                    throw new IllegalStateException("Unexpected exception occurred while parsing "
8168                            + parseResult.scanFile, throwable);
8169                }
8170
8171                // Delete invalid userdata apps
8172                if ((scanFlags & SCAN_AS_SYSTEM) == 0 &&
8173                        errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8174                    logCriticalInfo(Log.WARN,
8175                            "Deleting invalid package at " + parseResult.scanFile);
8176                    removeCodePathLI(parseResult.scanFile);
8177                }
8178            }
8179        }
8180    }
8181
8182    public static void reportSettingsProblem(int priority, String msg) {
8183        logCriticalInfo(priority, msg);
8184    }
8185
8186    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg,
8187            final @ParseFlags int parseFlags) throws PackageManagerException {
8188        // When upgrading from pre-N MR1, verify the package time stamp using the package
8189        // directory and not the APK file.
8190        final long lastModifiedTime = mIsPreNMR1Upgrade
8191                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg);
8192        if (ps != null
8193                && ps.codePathString.equals(pkg.codePath)
8194                && ps.timeStamp == lastModifiedTime
8195                && !isCompatSignatureUpdateNeeded(pkg)
8196                && !isRecoverSignatureUpdateNeeded(pkg)) {
8197            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8198            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
8199            ArraySet<PublicKey> signingKs;
8200            synchronized (mPackages) {
8201                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8202            }
8203            if (ps.signatures.mSignatures != null
8204                    && ps.signatures.mSignatures.length != 0
8205                    && signingKs != null) {
8206                // Optimization: reuse the existing cached certificates
8207                // if the package appears to be unchanged.
8208                pkg.mSignatures = ps.signatures.mSignatures;
8209                pkg.mSigningKeys = signingKs;
8210                return;
8211            }
8212
8213            Slog.w(TAG, "PackageSetting for " + ps.name
8214                    + " is missing signatures.  Collecting certs again to recover them.");
8215        } else {
8216            Slog.i(TAG, toString() + " changed; collecting certs");
8217        }
8218
8219        try {
8220            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8221            PackageParser.collectCertificates(pkg, parseFlags);
8222        } catch (PackageParserException e) {
8223            throw PackageManagerException.from(e);
8224        } finally {
8225            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8226        }
8227    }
8228
8229    /**
8230     *  Traces a package scan.
8231     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8232     */
8233    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8234            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8235        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8236        try {
8237            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8238        } finally {
8239            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8240        }
8241    }
8242
8243    /**
8244     *  Scans a package and returns the newly parsed package.
8245     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8246     */
8247    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8248            long currentTime, UserHandle user) throws PackageManagerException {
8249        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8250        PackageParser pp = new PackageParser();
8251        pp.setSeparateProcesses(mSeparateProcesses);
8252        pp.setOnlyCoreApps(mOnlyCore);
8253        pp.setDisplayMetrics(mMetrics);
8254        pp.setCallback(mPackageParserCallback);
8255
8256        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8257        final PackageParser.Package pkg;
8258        try {
8259            pkg = pp.parsePackage(scanFile, parseFlags);
8260        } catch (PackageParserException e) {
8261            throw PackageManagerException.from(e);
8262        } finally {
8263            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8264        }
8265
8266        // Static shared libraries have synthetic package names
8267        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8268            renameStaticSharedLibraryPackage(pkg);
8269        }
8270
8271        return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8272    }
8273
8274    /**
8275     *  Scans a package and returns the newly parsed package.
8276     *  @throws PackageManagerException on a parse error.
8277     */
8278    private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg,
8279            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8280            @Nullable UserHandle user)
8281                    throws PackageManagerException {
8282        // If the package has children and this is the first dive in the function
8283        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8284        // packages (parent and children) would be successfully scanned before the
8285        // actual scan since scanning mutates internal state and we want to atomically
8286        // install the package and its children.
8287        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8288            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8289                scanFlags |= SCAN_CHECK_ONLY;
8290            }
8291        } else {
8292            scanFlags &= ~SCAN_CHECK_ONLY;
8293        }
8294
8295        // Scan the parent
8296        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, parseFlags,
8297                scanFlags, currentTime, user);
8298
8299        // Scan the children
8300        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8301        for (int i = 0; i < childCount; i++) {
8302            PackageParser.Package childPackage = pkg.childPackages.get(i);
8303            scanPackageInternalLI(childPackage, parseFlags, scanFlags,
8304                    currentTime, user);
8305        }
8306
8307
8308        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8309            return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8310        }
8311
8312        return scannedPkg;
8313    }
8314
8315    /**
8316     *  Scans a package and returns the newly parsed package.
8317     *  @throws PackageManagerException on a parse error.
8318     */
8319    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg,
8320            @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8321            @Nullable UserHandle user)
8322                    throws PackageManagerException {
8323        PackageSetting ps = null;
8324        PackageSetting updatedPs;
8325        // reader
8326        synchronized (mPackages) {
8327            // Look to see if we already know about this package.
8328            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8329            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8330                // This package has been renamed to its original name.  Let's
8331                // use that.
8332                ps = mSettings.getPackageLPr(oldName);
8333            }
8334            // If there was no original package, see one for the real package name.
8335            if (ps == null) {
8336                ps = mSettings.getPackageLPr(pkg.packageName);
8337            }
8338            // Check to see if this package could be hiding/updating a system
8339            // package.  Must look for it either under the original or real
8340            // package name depending on our state.
8341            updatedPs = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8342            if (DEBUG_INSTALL && updatedPs != null) Slog.d(TAG, "updatedPkg = " + updatedPs);
8343
8344            // If this is a package we don't know about on the system partition, we
8345            // may need to remove disabled child packages on the system partition
8346            // or may need to not add child packages if the parent apk is updated
8347            // on the data partition and no longer defines this child package.
8348            if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
8349                // If this is a parent package for an updated system app and this system
8350                // app got an OTA update which no longer defines some of the child packages
8351                // we have to prune them from the disabled system packages.
8352                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8353                if (disabledPs != null) {
8354                    final int scannedChildCount = (pkg.childPackages != null)
8355                            ? pkg.childPackages.size() : 0;
8356                    final int disabledChildCount = disabledPs.childPackageNames != null
8357                            ? disabledPs.childPackageNames.size() : 0;
8358                    for (int i = 0; i < disabledChildCount; i++) {
8359                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8360                        boolean disabledPackageAvailable = false;
8361                        for (int j = 0; j < scannedChildCount; j++) {
8362                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8363                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8364                                disabledPackageAvailable = true;
8365                                break;
8366                            }
8367                         }
8368                         if (!disabledPackageAvailable) {
8369                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8370                         }
8371                    }
8372                }
8373            }
8374        }
8375
8376        final boolean isUpdatedPkg = updatedPs != null;
8377        final boolean isUpdatedSystemPkg = isUpdatedPkg && (scanFlags & SCAN_AS_SYSTEM) != 0;
8378        boolean isUpdatedPkgBetter = false;
8379        // First check if this is a system package that may involve an update
8380        if (isUpdatedSystemPkg) {
8381            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8382            // it needs to drop FLAG_PRIVILEGED.
8383            if (locationIsPrivileged(pkg.codePath)) {
8384                updatedPs.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8385            } else {
8386                updatedPs.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8387            }
8388            // If new package is not located in "/oem" (e.g. due to an OTA),
8389            // it needs to drop FLAG_OEM.
8390            if (locationIsOem(pkg.codePath)) {
8391                updatedPs.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
8392            } else {
8393                updatedPs.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_OEM;
8394            }
8395            // If new package is not located in "/vendor" (e.g. due to an OTA),
8396            // it needs to drop FLAG_VENDOR.
8397            if (locationIsVendor(pkg.codePath)) {
8398                updatedPs.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR;
8399            } else {
8400                updatedPs.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_VENDOR;
8401            }
8402
8403            if (ps != null && !ps.codePathString.equals(pkg.codePath)) {
8404                // The path has changed from what was last scanned...  check the
8405                // version of the new path against what we have stored to determine
8406                // what to do.
8407                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8408                if (pkg.getLongVersionCode() <= ps.versionCode) {
8409                    // The system package has been updated and the code path does not match
8410                    // Ignore entry. Skip it.
8411                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + pkg.codePath
8412                            + " ignored: updated version " + ps.versionCode
8413                            + " better than this " + pkg.getLongVersionCode());
8414                    if (!updatedPs.codePathString.equals(pkg.codePath)) {
8415                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8416                                + ps.name + " changing from " + updatedPs.codePathString
8417                                + " to " + pkg.codePath);
8418                        final File codePath = new File(pkg.codePath);
8419                        updatedPs.codePath = codePath;
8420                        updatedPs.codePathString = pkg.codePath;
8421                        updatedPs.resourcePath = codePath;
8422                        updatedPs.resourcePathString = pkg.codePath;
8423                    }
8424                    updatedPs.pkg = pkg;
8425                    updatedPs.versionCode = pkg.getLongVersionCode();
8426
8427                    // Update the disabled system child packages to point to the package too.
8428                    final int childCount = updatedPs.childPackageNames != null
8429                            ? updatedPs.childPackageNames.size() : 0;
8430                    for (int i = 0; i < childCount; i++) {
8431                        String childPackageName = updatedPs.childPackageNames.get(i);
8432                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8433                                childPackageName);
8434                        if (updatedChildPkg != null) {
8435                            updatedChildPkg.pkg = pkg;
8436                            updatedChildPkg.versionCode = pkg.getLongVersionCode();
8437                        }
8438                    }
8439                } else {
8440                    // The current app on the system partition is better than
8441                    // what we have updated to on the data partition; switch
8442                    // back to the system partition version.
8443                    // At this point, its safely assumed that package installation for
8444                    // apps in system partition will go through. If not there won't be a working
8445                    // version of the app
8446                    // writer
8447                    synchronized (mPackages) {
8448                        // Just remove the loaded entries from package lists.
8449                        mPackages.remove(ps.name);
8450                    }
8451
8452                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + pkg.codePath
8453                            + " reverting from " + ps.codePathString
8454                            + ": new version " + pkg.getLongVersionCode()
8455                            + " better than installed " + ps.versionCode);
8456
8457                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8458                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8459                    synchronized (mInstallLock) {
8460                        args.cleanUpResourcesLI();
8461                    }
8462                    synchronized (mPackages) {
8463                        mSettings.enableSystemPackageLPw(ps.name);
8464                    }
8465                    isUpdatedPkgBetter = true;
8466                }
8467            }
8468        }
8469
8470        String resourcePath = null;
8471        String baseResourcePath = null;
8472        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
8473            if (ps != null && ps.resourcePathString != null) {
8474                resourcePath = ps.resourcePathString;
8475                baseResourcePath = ps.resourcePathString;
8476            } else {
8477                // Should not happen at all. Just log an error.
8478                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
8479            }
8480        } else {
8481            resourcePath = pkg.codePath;
8482            baseResourcePath = pkg.baseCodePath;
8483        }
8484
8485        // Set application objects path explicitly.
8486        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8487        pkg.setApplicationInfoCodePath(pkg.codePath);
8488        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8489        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8490        pkg.setApplicationInfoResourcePath(resourcePath);
8491        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
8492        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8493
8494        // throw an exception if we have an update to a system application, but, it's not more
8495        // recent than the package we've already scanned
8496        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
8497            // Set CPU Abis to application info.
8498            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
8499                final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, updatedPs);
8500                derivePackageAbi(pkg, cpuAbiOverride, false);
8501            } else {
8502                pkg.applicationInfo.primaryCpuAbi = updatedPs.primaryCpuAbiString;
8503                pkg.applicationInfo.secondaryCpuAbi = updatedPs.secondaryCpuAbiString;
8504            }
8505            pkg.mExtras = updatedPs;
8506
8507            throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at "
8508                    + pkg.codePath + " ignored: updated version " + updatedPs.versionCode
8509                    + " better than this " + pkg.getLongVersionCode());
8510        }
8511
8512        if (isUpdatedPkg) {
8513            // updated system applications don't initially have the SCAN_AS_SYSTEM flag set
8514            scanFlags |= SCAN_AS_SYSTEM;
8515
8516            // An updated privileged application will not have the PARSE_IS_PRIVILEGED
8517            // flag set initially
8518            if ((updatedPs.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
8519                scanFlags |= SCAN_AS_PRIVILEGED;
8520            }
8521
8522            // An updated OEM app will not have the SCAN_AS_OEM
8523            // flag set initially
8524            if ((updatedPs.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
8525                scanFlags |= SCAN_AS_OEM;
8526            }
8527
8528            // An updated vendor app will not have the SCAN_AS_VENDOR
8529            // flag set initially
8530            if ((updatedPs.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) {
8531                scanFlags |= SCAN_AS_VENDOR;
8532            }
8533        }
8534
8535        // Verify certificates against what was last scanned
8536        collectCertificatesLI(ps, pkg, parseFlags);
8537
8538        /*
8539         * A new system app appeared, but we already had a non-system one of the
8540         * same name installed earlier.
8541         */
8542        boolean shouldHideSystemApp = false;
8543        if (!isUpdatedPkg && ps != null
8544                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
8545            /*
8546             * Check to make sure the signatures match first. If they don't,
8547             * wipe the installed application and its data.
8548             */
8549            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
8550                    != PackageManager.SIGNATURE_MATCH) {
8551                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
8552                        + " signatures don't match existing userdata copy; removing");
8553                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8554                        "scanPackageInternalLI")) {
8555                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8556                }
8557                ps = null;
8558            } else {
8559                /*
8560                 * If the newly-added system app is an older version than the
8561                 * already installed version, hide it. It will be scanned later
8562                 * and re-added like an update.
8563                 */
8564                if (pkg.getLongVersionCode() <= ps.versionCode) {
8565                    shouldHideSystemApp = true;
8566                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + pkg.codePath
8567                            + " but new version " + pkg.getLongVersionCode()
8568                            + " better than installed " + ps.versionCode + "; hiding system");
8569                } else {
8570                    /*
8571                     * The newly found system app is a newer version that the
8572                     * one previously installed. Simply remove the
8573                     * already-installed application and replace it with our own
8574                     * while keeping the application data.
8575                     */
8576                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + pkg.codePath
8577                            + " reverting from " + ps.codePathString + ": new version "
8578                            + pkg.getLongVersionCode() + " better than installed "
8579                            + ps.versionCode);
8580                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8581                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8582                    synchronized (mInstallLock) {
8583                        args.cleanUpResourcesLI();
8584                    }
8585                }
8586            }
8587        }
8588
8589        // The apk is forward locked (not public) if its code and resources
8590        // are kept in different files. (except for app in either system or
8591        // vendor path).
8592        // TODO grab this value from PackageSettings
8593        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8594            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
8595                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
8596            }
8597        }
8598
8599        final int userId = ((user == null) ? 0 : user.getIdentifier());
8600        if (ps != null && ps.getInstantApp(userId)) {
8601            scanFlags |= SCAN_AS_INSTANT_APP;
8602        }
8603        if (ps != null && ps.getVirtulalPreload(userId)) {
8604            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
8605        }
8606
8607        // Note that we invoke the following method only if we are about to unpack an application
8608        PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags
8609                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8610
8611        /*
8612         * If the system app should be overridden by a previously installed
8613         * data, hide the system app now and let the /data/app scan pick it up
8614         * again.
8615         */
8616        if (shouldHideSystemApp) {
8617            synchronized (mPackages) {
8618                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8619            }
8620        }
8621
8622        return scannedPkg;
8623    }
8624
8625    private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8626        // Derive the new package synthetic package name
8627        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8628                + pkg.staticSharedLibVersion);
8629    }
8630
8631    private static String fixProcessName(String defProcessName,
8632            String processName) {
8633        if (processName == null) {
8634            return defProcessName;
8635        }
8636        return processName;
8637    }
8638
8639    /**
8640     * Enforces that only the system UID or root's UID can call a method exposed
8641     * via Binder.
8642     *
8643     * @param message used as message if SecurityException is thrown
8644     * @throws SecurityException if the caller is not system or root
8645     */
8646    private static final void enforceSystemOrRoot(String message) {
8647        final int uid = Binder.getCallingUid();
8648        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8649            throw new SecurityException(message);
8650        }
8651    }
8652
8653    @Override
8654    public void performFstrimIfNeeded() {
8655        enforceSystemOrRoot("Only the system can request fstrim");
8656
8657        // Before everything else, see whether we need to fstrim.
8658        try {
8659            IStorageManager sm = PackageHelper.getStorageManager();
8660            if (sm != null) {
8661                boolean doTrim = false;
8662                final long interval = android.provider.Settings.Global.getLong(
8663                        mContext.getContentResolver(),
8664                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8665                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8666                if (interval > 0) {
8667                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8668                    if (timeSinceLast > interval) {
8669                        doTrim = true;
8670                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8671                                + "; running immediately");
8672                    }
8673                }
8674                if (doTrim) {
8675                    final boolean dexOptDialogShown;
8676                    synchronized (mPackages) {
8677                        dexOptDialogShown = mDexOptDialogShown;
8678                    }
8679                    if (!isFirstBoot() && dexOptDialogShown) {
8680                        try {
8681                            ActivityManager.getService().showBootMessage(
8682                                    mContext.getResources().getString(
8683                                            R.string.android_upgrading_fstrim), true);
8684                        } catch (RemoteException e) {
8685                        }
8686                    }
8687                    sm.runMaintenance();
8688                }
8689            } else {
8690                Slog.e(TAG, "storageManager service unavailable!");
8691            }
8692        } catch (RemoteException e) {
8693            // Can't happen; StorageManagerService is local
8694        }
8695    }
8696
8697    @Override
8698    public void updatePackagesIfNeeded() {
8699        enforceSystemOrRoot("Only the system can request package update");
8700
8701        // We need to re-extract after an OTA.
8702        boolean causeUpgrade = isUpgrade();
8703
8704        // First boot or factory reset.
8705        // Note: we also handle devices that are upgrading to N right now as if it is their
8706        //       first boot, as they do not have profile data.
8707        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8708
8709        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8710        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8711
8712        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8713            return;
8714        }
8715
8716        List<PackageParser.Package> pkgs;
8717        synchronized (mPackages) {
8718            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8719        }
8720
8721        final long startTime = System.nanoTime();
8722        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8723                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
8724                    false /* bootComplete */);
8725
8726        final int elapsedTimeSeconds =
8727                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8728
8729        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8730        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8731        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8732        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8733        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8734    }
8735
8736    /*
8737     * Return the prebuilt profile path given a package base code path.
8738     */
8739    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
8740        return pkg.baseCodePath + ".prof";
8741    }
8742
8743    /**
8744     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8745     * containing statistics about the invocation. The array consists of three elements,
8746     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8747     * and {@code numberOfPackagesFailed}.
8748     */
8749    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8750            final String compilerFilter, boolean bootComplete) {
8751
8752        int numberOfPackagesVisited = 0;
8753        int numberOfPackagesOptimized = 0;
8754        int numberOfPackagesSkipped = 0;
8755        int numberOfPackagesFailed = 0;
8756        final int numberOfPackagesToDexopt = pkgs.size();
8757
8758        for (PackageParser.Package pkg : pkgs) {
8759            numberOfPackagesVisited++;
8760
8761            boolean useProfileForDexopt = false;
8762
8763            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
8764                // Copy over initial preopt profiles since we won't get any JIT samples for methods
8765                // that are already compiled.
8766                File profileFile = new File(getPrebuildProfilePath(pkg));
8767                // Copy profile if it exists.
8768                if (profileFile.exists()) {
8769                    try {
8770                        // We could also do this lazily before calling dexopt in
8771                        // PackageDexOptimizer to prevent this happening on first boot. The issue
8772                        // is that we don't have a good way to say "do this only once".
8773                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8774                                pkg.applicationInfo.uid, pkg.packageName)) {
8775                            Log.e(TAG, "Installer failed to copy system profile!");
8776                        } else {
8777                            // Disabled as this causes speed-profile compilation during first boot
8778                            // even if things are already compiled.
8779                            // useProfileForDexopt = true;
8780                        }
8781                    } catch (Exception e) {
8782                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
8783                                e);
8784                    }
8785                } else {
8786                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8787                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
8788                    // minimize the number off apps being speed-profile compiled during first boot.
8789                    // The other paths will not change the filter.
8790                    if (disabledPs != null && disabledPs.pkg.isStub) {
8791                        // The package is the stub one, remove the stub suffix to get the normal
8792                        // package and APK names.
8793                        String systemProfilePath =
8794                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
8795                        profileFile = new File(systemProfilePath);
8796                        // If we have a profile for a compressed APK, copy it to the reference
8797                        // location.
8798                        // Note that copying the profile here will cause it to override the
8799                        // reference profile every OTA even though the existing reference profile
8800                        // may have more data. We can't copy during decompression since the
8801                        // directories are not set up at that point.
8802                        if (profileFile.exists()) {
8803                            try {
8804                                // We could also do this lazily before calling dexopt in
8805                                // PackageDexOptimizer to prevent this happening on first boot. The
8806                                // issue is that we don't have a good way to say "do this only
8807                                // once".
8808                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8809                                        pkg.applicationInfo.uid, pkg.packageName)) {
8810                                    Log.e(TAG, "Failed to copy system profile for stub package!");
8811                                } else {
8812                                    useProfileForDexopt = true;
8813                                }
8814                            } catch (Exception e) {
8815                                Log.e(TAG, "Failed to copy profile " +
8816                                        profileFile.getAbsolutePath() + " ", e);
8817                            }
8818                        }
8819                    }
8820                }
8821            }
8822
8823            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8824                if (DEBUG_DEXOPT) {
8825                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8826                }
8827                numberOfPackagesSkipped++;
8828                continue;
8829            }
8830
8831            if (DEBUG_DEXOPT) {
8832                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8833                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8834            }
8835
8836            if (showDialog) {
8837                try {
8838                    ActivityManager.getService().showBootMessage(
8839                            mContext.getResources().getString(R.string.android_upgrading_apk,
8840                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8841                } catch (RemoteException e) {
8842                }
8843                synchronized (mPackages) {
8844                    mDexOptDialogShown = true;
8845                }
8846            }
8847
8848            String pkgCompilerFilter = compilerFilter;
8849            if (useProfileForDexopt) {
8850                // Use background dexopt mode to try and use the profile. Note that this does not
8851                // guarantee usage of the profile.
8852                pkgCompilerFilter =
8853                        PackageManagerServiceCompilerMapping.getCompilerFilterForReason(
8854                                PackageManagerService.REASON_BACKGROUND_DEXOPT);
8855            }
8856
8857            // checkProfiles is false to avoid merging profiles during boot which
8858            // might interfere with background compilation (b/28612421).
8859            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8860            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8861            // trade-off worth doing to save boot time work.
8862            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
8863            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
8864                    pkg.packageName,
8865                    pkgCompilerFilter,
8866                    dexoptFlags));
8867
8868            switch (primaryDexOptStaus) {
8869                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8870                    numberOfPackagesOptimized++;
8871                    break;
8872                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8873                    numberOfPackagesSkipped++;
8874                    break;
8875                case PackageDexOptimizer.DEX_OPT_FAILED:
8876                    numberOfPackagesFailed++;
8877                    break;
8878                default:
8879                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
8880                    break;
8881            }
8882        }
8883
8884        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8885                numberOfPackagesFailed };
8886    }
8887
8888    @Override
8889    public void notifyPackageUse(String packageName, int reason) {
8890        synchronized (mPackages) {
8891            final int callingUid = Binder.getCallingUid();
8892            final int callingUserId = UserHandle.getUserId(callingUid);
8893            if (getInstantAppPackageName(callingUid) != null) {
8894                if (!isCallerSameApp(packageName, callingUid)) {
8895                    return;
8896                }
8897            } else {
8898                if (isInstantApp(packageName, callingUserId)) {
8899                    return;
8900                }
8901            }
8902            notifyPackageUseLocked(packageName, reason);
8903        }
8904    }
8905
8906    private void notifyPackageUseLocked(String packageName, int reason) {
8907        final PackageParser.Package p = mPackages.get(packageName);
8908        if (p == null) {
8909            return;
8910        }
8911        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
8912    }
8913
8914    @Override
8915    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
8916            List<String> classPaths, String loaderIsa) {
8917        int userId = UserHandle.getCallingUserId();
8918        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
8919        if (ai == null) {
8920            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
8921                + loadingPackageName + ", user=" + userId);
8922            return;
8923        }
8924        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
8925    }
8926
8927    @Override
8928    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
8929            IDexModuleRegisterCallback callback) {
8930        int userId = UserHandle.getCallingUserId();
8931        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
8932        DexManager.RegisterDexModuleResult result;
8933        if (ai == null) {
8934            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
8935                     " calling user. package=" + packageName + ", user=" + userId);
8936            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
8937        } else {
8938            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
8939        }
8940
8941        if (callback != null) {
8942            mHandler.post(() -> {
8943                try {
8944                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
8945                } catch (RemoteException e) {
8946                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
8947                }
8948            });
8949        }
8950    }
8951
8952    /**
8953     * Ask the package manager to perform a dex-opt with the given compiler filter.
8954     *
8955     * Note: exposed only for the shell command to allow moving packages explicitly to a
8956     *       definite state.
8957     */
8958    @Override
8959    public boolean performDexOptMode(String packageName,
8960            boolean checkProfiles, String targetCompilerFilter, boolean force,
8961            boolean bootComplete, String splitName) {
8962        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
8963                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
8964                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
8965        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
8966                splitName, flags));
8967    }
8968
8969    /**
8970     * Ask the package manager to perform a dex-opt with the given compiler filter on the
8971     * secondary dex files belonging to the given package.
8972     *
8973     * Note: exposed only for the shell command to allow moving packages explicitly to a
8974     *       definite state.
8975     */
8976    @Override
8977    public boolean performDexOptSecondary(String packageName, String compilerFilter,
8978            boolean force) {
8979        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
8980                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
8981                DexoptOptions.DEXOPT_BOOT_COMPLETE |
8982                (force ? DexoptOptions.DEXOPT_FORCE : 0);
8983        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
8984    }
8985
8986    /*package*/ boolean performDexOpt(DexoptOptions options) {
8987        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8988            return false;
8989        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
8990            return false;
8991        }
8992
8993        if (options.isDexoptOnlySecondaryDex()) {
8994            return mDexManager.dexoptSecondaryDex(options);
8995        } else {
8996            int dexoptStatus = performDexOptWithStatus(options);
8997            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8998        }
8999    }
9000
9001    /**
9002     * Perform dexopt on the given package and return one of following result:
9003     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9004     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9005     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9006     */
9007    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9008        return performDexOptTraced(options);
9009    }
9010
9011    private int performDexOptTraced(DexoptOptions options) {
9012        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9013        try {
9014            return performDexOptInternal(options);
9015        } finally {
9016            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9017        }
9018    }
9019
9020    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9021    // if the package can now be considered up to date for the given filter.
9022    private int performDexOptInternal(DexoptOptions options) {
9023        PackageParser.Package p;
9024        synchronized (mPackages) {
9025            p = mPackages.get(options.getPackageName());
9026            if (p == null) {
9027                // Package could not be found. Report failure.
9028                return PackageDexOptimizer.DEX_OPT_FAILED;
9029            }
9030            mPackageUsage.maybeWriteAsync(mPackages);
9031            mCompilerStats.maybeWriteAsync();
9032        }
9033        long callingId = Binder.clearCallingIdentity();
9034        try {
9035            synchronized (mInstallLock) {
9036                return performDexOptInternalWithDependenciesLI(p, options);
9037            }
9038        } finally {
9039            Binder.restoreCallingIdentity(callingId);
9040        }
9041    }
9042
9043    public ArraySet<String> getOptimizablePackages() {
9044        ArraySet<String> pkgs = new ArraySet<String>();
9045        synchronized (mPackages) {
9046            for (PackageParser.Package p : mPackages.values()) {
9047                if (PackageDexOptimizer.canOptimizePackage(p)) {
9048                    pkgs.add(p.packageName);
9049                }
9050            }
9051        }
9052        return pkgs;
9053    }
9054
9055    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9056            DexoptOptions options) {
9057        // Select the dex optimizer based on the force parameter.
9058        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9059        //       allocate an object here.
9060        PackageDexOptimizer pdo = options.isForce()
9061                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9062                : mPackageDexOptimizer;
9063
9064        // Dexopt all dependencies first. Note: we ignore the return value and march on
9065        // on errors.
9066        // Note that we are going to call performDexOpt on those libraries as many times as
9067        // they are referenced in packages. When we do a batch of performDexOpt (for example
9068        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9069        // and the first package that uses the library will dexopt it. The
9070        // others will see that the compiled code for the library is up to date.
9071        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9072        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9073        if (!deps.isEmpty()) {
9074            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9075                    options.getCompilerFilter(), options.getSplitName(),
9076                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9077            for (PackageParser.Package depPackage : deps) {
9078                // TODO: Analyze and investigate if we (should) profile libraries.
9079                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9080                        getOrCreateCompilerPackageStats(depPackage),
9081                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9082            }
9083        }
9084        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9085                getOrCreateCompilerPackageStats(p),
9086                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9087    }
9088
9089    /**
9090     * Reconcile the information we have about the secondary dex files belonging to
9091     * {@code packagName} and the actual dex files. For all dex files that were
9092     * deleted, update the internal records and delete the generated oat files.
9093     */
9094    @Override
9095    public void reconcileSecondaryDexFiles(String packageName) {
9096        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9097            return;
9098        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9099            return;
9100        }
9101        mDexManager.reconcileSecondaryDexFiles(packageName);
9102    }
9103
9104    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9105    // a reference there.
9106    /*package*/ DexManager getDexManager() {
9107        return mDexManager;
9108    }
9109
9110    /**
9111     * Execute the background dexopt job immediately.
9112     */
9113    @Override
9114    public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) {
9115        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9116            return false;
9117        }
9118        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames);
9119    }
9120
9121    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9122        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9123                || p.usesStaticLibraries != null) {
9124            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9125            Set<String> collectedNames = new HashSet<>();
9126            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9127
9128            retValue.remove(p);
9129
9130            return retValue;
9131        } else {
9132            return Collections.emptyList();
9133        }
9134    }
9135
9136    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9137            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9138        if (!collectedNames.contains(p.packageName)) {
9139            collectedNames.add(p.packageName);
9140            collected.add(p);
9141
9142            if (p.usesLibraries != null) {
9143                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9144                        null, collected, collectedNames);
9145            }
9146            if (p.usesOptionalLibraries != null) {
9147                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9148                        null, collected, collectedNames);
9149            }
9150            if (p.usesStaticLibraries != null) {
9151                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9152                        p.usesStaticLibrariesVersions, collected, collectedNames);
9153            }
9154        }
9155    }
9156
9157    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions,
9158            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9159        final int libNameCount = libs.size();
9160        for (int i = 0; i < libNameCount; i++) {
9161            String libName = libs.get(i);
9162            long version = (versions != null && versions.length == libNameCount)
9163                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9164            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9165            if (libPkg != null) {
9166                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9167            }
9168        }
9169    }
9170
9171    private PackageParser.Package findSharedNonSystemLibrary(String name, long version) {
9172        synchronized (mPackages) {
9173            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9174            if (libEntry != null) {
9175                return mPackages.get(libEntry.apk);
9176            }
9177            return null;
9178        }
9179    }
9180
9181    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) {
9182        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9183        if (versionedLib == null) {
9184            return null;
9185        }
9186        return versionedLib.get(version);
9187    }
9188
9189    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9190        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9191                pkg.staticSharedLibName);
9192        if (versionedLib == null) {
9193            return null;
9194        }
9195        long previousLibVersion = -1;
9196        final int versionCount = versionedLib.size();
9197        for (int i = 0; i < versionCount; i++) {
9198            final long libVersion = versionedLib.keyAt(i);
9199            if (libVersion < pkg.staticSharedLibVersion) {
9200                previousLibVersion = Math.max(previousLibVersion, libVersion);
9201            }
9202        }
9203        if (previousLibVersion >= 0) {
9204            return versionedLib.get(previousLibVersion);
9205        }
9206        return null;
9207    }
9208
9209    public void shutdown() {
9210        mPackageUsage.writeNow(mPackages);
9211        mCompilerStats.writeNow();
9212        mDexManager.writePackageDexUsageNow();
9213    }
9214
9215    @Override
9216    public void dumpProfiles(String packageName) {
9217        PackageParser.Package pkg;
9218        synchronized (mPackages) {
9219            pkg = mPackages.get(packageName);
9220            if (pkg == null) {
9221                throw new IllegalArgumentException("Unknown package: " + packageName);
9222            }
9223        }
9224        /* Only the shell, root, or the app user should be able to dump profiles. */
9225        int callingUid = Binder.getCallingUid();
9226        if (callingUid != Process.SHELL_UID &&
9227            callingUid != Process.ROOT_UID &&
9228            callingUid != pkg.applicationInfo.uid) {
9229            throw new SecurityException("dumpProfiles");
9230        }
9231
9232        synchronized (mInstallLock) {
9233            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9234            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9235            try {
9236                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9237                String codePaths = TextUtils.join(";", allCodePaths);
9238                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9239            } catch (InstallerException e) {
9240                Slog.w(TAG, "Failed to dump profiles", e);
9241            }
9242            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9243        }
9244    }
9245
9246    @Override
9247    public void forceDexOpt(String packageName) {
9248        enforceSystemOrRoot("forceDexOpt");
9249
9250        PackageParser.Package pkg;
9251        synchronized (mPackages) {
9252            pkg = mPackages.get(packageName);
9253            if (pkg == null) {
9254                throw new IllegalArgumentException("Unknown package: " + packageName);
9255            }
9256        }
9257
9258        synchronized (mInstallLock) {
9259            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9260
9261            // Whoever is calling forceDexOpt wants a compiled package.
9262            // Don't use profiles since that may cause compilation to be skipped.
9263            final int res = performDexOptInternalWithDependenciesLI(
9264                    pkg,
9265                    new DexoptOptions(packageName,
9266                            getDefaultCompilerFilter(),
9267                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9268
9269            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9270            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9271                throw new IllegalStateException("Failed to dexopt: " + res);
9272            }
9273        }
9274    }
9275
9276    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9277        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9278            Slog.w(TAG, "Unable to update from " + oldPkg.name
9279                    + " to " + newPkg.packageName
9280                    + ": old package not in system partition");
9281            return false;
9282        } else if (mPackages.get(oldPkg.name) != null) {
9283            Slog.w(TAG, "Unable to update from " + oldPkg.name
9284                    + " to " + newPkg.packageName
9285                    + ": old package still exists");
9286            return false;
9287        }
9288        return true;
9289    }
9290
9291    void removeCodePathLI(File codePath) {
9292        if (codePath.isDirectory()) {
9293            try {
9294                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9295            } catch (InstallerException e) {
9296                Slog.w(TAG, "Failed to remove code path", e);
9297            }
9298        } else {
9299            codePath.delete();
9300        }
9301    }
9302
9303    private int[] resolveUserIds(int userId) {
9304        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9305    }
9306
9307    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9308        if (pkg == null) {
9309            Slog.wtf(TAG, "Package was null!", new Throwable());
9310            return;
9311        }
9312        clearAppDataLeafLIF(pkg, userId, flags);
9313        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9314        for (int i = 0; i < childCount; i++) {
9315            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9316        }
9317    }
9318
9319    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9320        final PackageSetting ps;
9321        synchronized (mPackages) {
9322            ps = mSettings.mPackages.get(pkg.packageName);
9323        }
9324        for (int realUserId : resolveUserIds(userId)) {
9325            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9326            try {
9327                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9328                        ceDataInode);
9329            } catch (InstallerException e) {
9330                Slog.w(TAG, String.valueOf(e));
9331            }
9332        }
9333    }
9334
9335    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9336        if (pkg == null) {
9337            Slog.wtf(TAG, "Package was null!", new Throwable());
9338            return;
9339        }
9340        destroyAppDataLeafLIF(pkg, userId, flags);
9341        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9342        for (int i = 0; i < childCount; i++) {
9343            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9344        }
9345    }
9346
9347    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9348        final PackageSetting ps;
9349        synchronized (mPackages) {
9350            ps = mSettings.mPackages.get(pkg.packageName);
9351        }
9352        for (int realUserId : resolveUserIds(userId)) {
9353            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9354            try {
9355                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9356                        ceDataInode);
9357            } catch (InstallerException e) {
9358                Slog.w(TAG, String.valueOf(e));
9359            }
9360            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9361        }
9362    }
9363
9364    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9365        if (pkg == null) {
9366            Slog.wtf(TAG, "Package was null!", new Throwable());
9367            return;
9368        }
9369        destroyAppProfilesLeafLIF(pkg);
9370        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9371        for (int i = 0; i < childCount; i++) {
9372            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9373        }
9374    }
9375
9376    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9377        try {
9378            mInstaller.destroyAppProfiles(pkg.packageName);
9379        } catch (InstallerException e) {
9380            Slog.w(TAG, String.valueOf(e));
9381        }
9382    }
9383
9384    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9385        if (pkg == null) {
9386            Slog.wtf(TAG, "Package was null!", new Throwable());
9387            return;
9388        }
9389        clearAppProfilesLeafLIF(pkg);
9390        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9391        for (int i = 0; i < childCount; i++) {
9392            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9393        }
9394    }
9395
9396    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9397        try {
9398            mInstaller.clearAppProfiles(pkg.packageName);
9399        } catch (InstallerException e) {
9400            Slog.w(TAG, String.valueOf(e));
9401        }
9402    }
9403
9404    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9405            long lastUpdateTime) {
9406        // Set parent install/update time
9407        PackageSetting ps = (PackageSetting) pkg.mExtras;
9408        if (ps != null) {
9409            ps.firstInstallTime = firstInstallTime;
9410            ps.lastUpdateTime = lastUpdateTime;
9411        }
9412        // Set children install/update time
9413        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9414        for (int i = 0; i < childCount; i++) {
9415            PackageParser.Package childPkg = pkg.childPackages.get(i);
9416            ps = (PackageSetting) childPkg.mExtras;
9417            if (ps != null) {
9418                ps.firstInstallTime = firstInstallTime;
9419                ps.lastUpdateTime = lastUpdateTime;
9420            }
9421        }
9422    }
9423
9424    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9425            SharedLibraryEntry file,
9426            PackageParser.Package changingLib) {
9427        if (file.path != null) {
9428            usesLibraryFiles.add(file.path);
9429            return;
9430        }
9431        PackageParser.Package p = mPackages.get(file.apk);
9432        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9433            // If we are doing this while in the middle of updating a library apk,
9434            // then we need to make sure to use that new apk for determining the
9435            // dependencies here.  (We haven't yet finished committing the new apk
9436            // to the package manager state.)
9437            if (p == null || p.packageName.equals(changingLib.packageName)) {
9438                p = changingLib;
9439            }
9440        }
9441        if (p != null) {
9442            usesLibraryFiles.addAll(p.getAllCodePaths());
9443            if (p.usesLibraryFiles != null) {
9444                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9445            }
9446        }
9447    }
9448
9449    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9450            PackageParser.Package changingLib) throws PackageManagerException {
9451        if (pkg == null) {
9452            return;
9453        }
9454        // The collection used here must maintain the order of addition (so
9455        // that libraries are searched in the correct order) and must have no
9456        // duplicates.
9457        Set<String> usesLibraryFiles = null;
9458        if (pkg.usesLibraries != null) {
9459            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9460                    null, null, pkg.packageName, changingLib, true,
9461                    pkg.applicationInfo.targetSdkVersion, null);
9462        }
9463        if (pkg.usesStaticLibraries != null) {
9464            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9465                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9466                    pkg.packageName, changingLib, true,
9467                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9468        }
9469        if (pkg.usesOptionalLibraries != null) {
9470            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9471                    null, null, pkg.packageName, changingLib, false,
9472                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9473        }
9474        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9475            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9476        } else {
9477            pkg.usesLibraryFiles = null;
9478        }
9479    }
9480
9481    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9482            @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests,
9483            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9484            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
9485            throws PackageManagerException {
9486        final int libCount = requestedLibraries.size();
9487        for (int i = 0; i < libCount; i++) {
9488            final String libName = requestedLibraries.get(i);
9489            final long libVersion = requiredVersions != null ? requiredVersions[i]
9490                    : SharedLibraryInfo.VERSION_UNDEFINED;
9491            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9492            if (libEntry == null) {
9493                if (required) {
9494                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9495                            "Package " + packageName + " requires unavailable shared library "
9496                                    + libName + "; failing!");
9497                } else if (DEBUG_SHARED_LIBRARIES) {
9498                    Slog.i(TAG, "Package " + packageName
9499                            + " desires unavailable shared library "
9500                            + libName + "; ignoring!");
9501                }
9502            } else {
9503                if (requiredVersions != null && requiredCertDigests != null) {
9504                    if (libEntry.info.getLongVersion() != requiredVersions[i]) {
9505                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9506                            "Package " + packageName + " requires unavailable static shared"
9507                                    + " library " + libName + " version "
9508                                    + libEntry.info.getLongVersion() + "; failing!");
9509                    }
9510
9511                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9512                    if (libPkg == null) {
9513                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9514                                "Package " + packageName + " requires unavailable static shared"
9515                                        + " library; failing!");
9516                    }
9517
9518                    final String[] expectedCertDigests = requiredCertDigests[i];
9519                    // For apps targeting O MR1 we require explicit enumeration of all certs.
9520                    final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
9521                            ? PackageUtils.computeSignaturesSha256Digests(libPkg.mSignatures)
9522                            : PackageUtils.computeSignaturesSha256Digests(
9523                                    new Signature[]{libPkg.mSignatures[0]});
9524
9525                    // Take a shortcut if sizes don't match. Note that if an app doesn't
9526                    // target O we don't parse the "additional-certificate" tags similarly
9527                    // how we only consider all certs only for apps targeting O (see above).
9528                    // Therefore, the size check is safe to make.
9529                    if (expectedCertDigests.length != libCertDigests.length) {
9530                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9531                                "Package " + packageName + " requires differently signed" +
9532                                        " static shared library; failing!");
9533                    }
9534
9535                    // Use a predictable order as signature order may vary
9536                    Arrays.sort(libCertDigests);
9537                    Arrays.sort(expectedCertDigests);
9538
9539                    final int certCount = libCertDigests.length;
9540                    for (int j = 0; j < certCount; j++) {
9541                        if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
9542                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9543                                    "Package " + packageName + " requires differently signed" +
9544                                            " static shared library; failing!");
9545                        }
9546                    }
9547                }
9548
9549                if (outUsedLibraries == null) {
9550                    // Use LinkedHashSet to preserve the order of files added to
9551                    // usesLibraryFiles while eliminating duplicates.
9552                    outUsedLibraries = new LinkedHashSet<>();
9553                }
9554                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9555            }
9556        }
9557        return outUsedLibraries;
9558    }
9559
9560    private static boolean hasString(List<String> list, List<String> which) {
9561        if (list == null) {
9562            return false;
9563        }
9564        for (int i=list.size()-1; i>=0; i--) {
9565            for (int j=which.size()-1; j>=0; j--) {
9566                if (which.get(j).equals(list.get(i))) {
9567                    return true;
9568                }
9569            }
9570        }
9571        return false;
9572    }
9573
9574    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9575            PackageParser.Package changingPkg) {
9576        ArrayList<PackageParser.Package> res = null;
9577        for (PackageParser.Package pkg : mPackages.values()) {
9578            if (changingPkg != null
9579                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9580                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9581                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9582                            changingPkg.staticSharedLibName)) {
9583                return null;
9584            }
9585            if (res == null) {
9586                res = new ArrayList<>();
9587            }
9588            res.add(pkg);
9589            try {
9590                updateSharedLibrariesLPr(pkg, changingPkg);
9591            } catch (PackageManagerException e) {
9592                // If a system app update or an app and a required lib missing we
9593                // delete the package and for updated system apps keep the data as
9594                // it is better for the user to reinstall than to be in an limbo
9595                // state. Also libs disappearing under an app should never happen
9596                // - just in case.
9597                if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) {
9598                    final int flags = pkg.isUpdatedSystemApp()
9599                            ? PackageManager.DELETE_KEEP_DATA : 0;
9600                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9601                            flags , null, true, null);
9602                }
9603                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9604            }
9605        }
9606        return res;
9607    }
9608
9609    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9610            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9611            @Nullable UserHandle user) throws PackageManagerException {
9612        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9613        // If the package has children and this is the first dive in the function
9614        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9615        // whether all packages (parent and children) would be successfully scanned
9616        // before the actual scan since scanning mutates internal state and we want
9617        // to atomically install the package and its children.
9618        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9619            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9620                scanFlags |= SCAN_CHECK_ONLY;
9621            }
9622        } else {
9623            scanFlags &= ~SCAN_CHECK_ONLY;
9624        }
9625
9626        final PackageParser.Package scannedPkg;
9627        try {
9628            // Scan the parent
9629            scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user);
9630            // Scan the children
9631            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9632            for (int i = 0; i < childCount; i++) {
9633                PackageParser.Package childPkg = pkg.childPackages.get(i);
9634                scanPackageNewLI(childPkg, parseFlags,
9635                        scanFlags, currentTime, user);
9636            }
9637        } finally {
9638            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9639        }
9640
9641        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9642            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
9643        }
9644
9645        return scannedPkg;
9646    }
9647
9648    /** The result of a package scan. */
9649    private static class ScanResult {
9650        /** Whether or not the package scan was successful */
9651        public final boolean success;
9652        /**
9653         * The final package settings. This may be the same object passed in
9654         * the {@link ScanRequest}, but, with modified values.
9655         */
9656        @Nullable public final PackageSetting pkgSetting;
9657        /** ABI code paths that have changed in the package scan */
9658        @Nullable public final List<String> changedAbiCodePath;
9659        public ScanResult(
9660                boolean success,
9661                @Nullable PackageSetting pkgSetting,
9662                @Nullable List<String> changedAbiCodePath) {
9663            this.success = success;
9664            this.pkgSetting = pkgSetting;
9665            this.changedAbiCodePath = changedAbiCodePath;
9666        }
9667    }
9668
9669    /** A package to be scanned */
9670    private static class ScanRequest {
9671        /** The parsed package */
9672        @NonNull public final PackageParser.Package pkg;
9673        /** Shared user settings, if the package has a shared user */
9674        @Nullable public final SharedUserSetting sharedUserSetting;
9675        /**
9676         * Package settings of the currently installed version.
9677         * <p><em>IMPORTANT:</em> The contents of this object may be modified
9678         * during scan.
9679         */
9680        @Nullable public final PackageSetting pkgSetting;
9681        /** A copy of the settings for the currently installed version */
9682        @Nullable public final PackageSetting oldPkgSetting;
9683        /** Package settings for the disabled version on the /system partition */
9684        @Nullable public final PackageSetting disabledPkgSetting;
9685        /** Package settings for the installed version under its original package name */
9686        @Nullable public final PackageSetting originalPkgSetting;
9687        /** The real package name of a renamed application */
9688        @Nullable public final String realPkgName;
9689        public final @ParseFlags int parseFlags;
9690        public final @ScanFlags int scanFlags;
9691        /** The user for which the package is being scanned */
9692        @Nullable public final UserHandle user;
9693        /** Whether or not the platform package is being scanned */
9694        public final boolean isPlatformPackage;
9695        public ScanRequest(
9696                @NonNull PackageParser.Package pkg,
9697                @Nullable SharedUserSetting sharedUserSetting,
9698                @Nullable PackageSetting pkgSetting,
9699                @Nullable PackageSetting disabledPkgSetting,
9700                @Nullable PackageSetting originalPkgSetting,
9701                @Nullable String realPkgName,
9702                @ParseFlags int parseFlags,
9703                @ScanFlags int scanFlags,
9704                boolean isPlatformPackage,
9705                @Nullable UserHandle user) {
9706            this.pkg = pkg;
9707            this.pkgSetting = pkgSetting;
9708            this.sharedUserSetting = sharedUserSetting;
9709            this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting);
9710            this.disabledPkgSetting = disabledPkgSetting;
9711            this.originalPkgSetting = originalPkgSetting;
9712            this.realPkgName = realPkgName;
9713            this.parseFlags = parseFlags;
9714            this.scanFlags = scanFlags;
9715            this.isPlatformPackage = isPlatformPackage;
9716            this.user = user;
9717        }
9718    }
9719
9720    @GuardedBy("mInstallLock")
9721    private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg,
9722            final @ParseFlags int parseFlags, final @ScanFlags int scanFlags, long currentTime,
9723            @Nullable UserHandle user) throws PackageManagerException {
9724
9725        final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9726        final String realPkgName = getRealPackageName(pkg, renamedPkgName);
9727        if (realPkgName != null) {
9728            ensurePackageRenamed(pkg, renamedPkgName);
9729        }
9730        final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
9731        final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9732        final PackageSetting disabledPkgSetting =
9733                mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9734
9735        if (mTransferedPackages.contains(pkg.packageName)) {
9736            Slog.w(TAG, "Package " + pkg.packageName
9737                    + " was transferred to another, but its .apk remains");
9738        }
9739
9740        synchronized (mPackages) {
9741            applyPolicy(pkg, parseFlags, scanFlags);
9742            assertPackageIsValid(pkg, parseFlags, scanFlags);
9743
9744            SharedUserSetting sharedUserSetting = null;
9745            if (pkg.mSharedUserId != null) {
9746                // SIDE EFFECTS; may potentially allocate a new shared user
9747                sharedUserSetting = mSettings.getSharedUserLPw(
9748                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9749                if (DEBUG_PACKAGE_SCANNING) {
9750                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
9751                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
9752                                + " (uid=" + sharedUserSetting.userId + "):"
9753                                + " packages=" + sharedUserSetting.packages);
9754                }
9755            }
9756
9757            boolean scanSucceeded = false;
9758            try {
9759                final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, pkgSetting,
9760                        disabledPkgSetting, originalPkgSetting, realPkgName, parseFlags, scanFlags,
9761                        (pkg == mPlatformPackage), user);
9762                final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime);
9763                if (result.success) {
9764                    commitScanResultsLocked(request, result);
9765                }
9766                scanSucceeded = true;
9767            } finally {
9768                  if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9769                      // DELETE_DATA_ON_FAILURES is only used by frozen paths
9770                      destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9771                              StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9772                      destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9773                  }
9774            }
9775        }
9776        return pkg;
9777    }
9778
9779    /**
9780     * Commits the package scan and modifies system state.
9781     * <p><em>WARNING:</em> The method may throw an excpetion in the middle
9782     * of committing the package, leaving the system in an inconsistent state.
9783     * This needs to be fixed so, once we get to this point, no errors are
9784     * possible and the system is not left in an inconsistent state.
9785     */
9786    @GuardedBy("mPackages")
9787    private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result)
9788            throws PackageManagerException {
9789        final PackageParser.Package pkg = request.pkg;
9790        final @ParseFlags int parseFlags = request.parseFlags;
9791        final @ScanFlags int scanFlags = request.scanFlags;
9792        final PackageSetting oldPkgSetting = request.oldPkgSetting;
9793        final PackageSetting originalPkgSetting = request.originalPkgSetting;
9794        final UserHandle user = request.user;
9795        final String realPkgName = request.realPkgName;
9796        final PackageSetting pkgSetting = result.pkgSetting;
9797        final List<String> changedAbiCodePath = result.changedAbiCodePath;
9798        final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting);
9799
9800        if (newPkgSettingCreated) {
9801            if (originalPkgSetting != null) {
9802                mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name);
9803            }
9804            // THROWS: when we can't allocate a user id. add call to check if there's
9805            // enough space to ensure we won't throw; otherwise, don't modify state
9806            mSettings.addUserToSettingLPw(pkgSetting);
9807
9808            if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) {
9809                mTransferedPackages.add(originalPkgSetting.name);
9810            }
9811        }
9812        // TODO(toddke): Consider a method specifically for modifying the Package object
9813        // post scan; or, moving this stuff out of the Package object since it has nothing
9814        // to do with the package on disk.
9815        // We need to have this here because addUserToSettingLPw() is sometimes responsible
9816        // for creating the application ID. If we did this earlier, we would be saving the
9817        // correct ID.
9818        pkg.applicationInfo.uid = pkgSetting.appId;
9819
9820        mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9821
9822        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) {
9823            mTransferedPackages.add(pkg.packageName);
9824        }
9825
9826        // THROWS: when requested libraries that can't be found. it only changes
9827        // the state of the passed in pkg object, so, move to the top of the method
9828        // and allow it to abort
9829        if ((scanFlags & SCAN_BOOTING) == 0
9830                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9831            // Check all shared libraries and map to their actual file path.
9832            // We only do this here for apps not on a system dir, because those
9833            // are the only ones that can fail an install due to this.  We
9834            // will take care of the system apps by updating all of their
9835            // library paths after the scan is done. Also during the initial
9836            // scan don't update any libs as we do this wholesale after all
9837            // apps are scanned to avoid dependency based scanning.
9838            updateSharedLibrariesLPr(pkg, null);
9839        }
9840
9841        // All versions of a static shared library are referenced with the same
9842        // package name. Internally, we use a synthetic package name to allow
9843        // multiple versions of the same shared library to be installed. So,
9844        // we need to generate the synthetic package name of the latest shared
9845        // library in order to compare signatures.
9846        PackageSetting signatureCheckPs = pkgSetting;
9847        if (pkg.applicationInfo.isStaticSharedLibrary()) {
9848            SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
9849            if (libraryEntry != null) {
9850                signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
9851            }
9852        }
9853
9854        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
9855        if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
9856            if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
9857                // We just determined the app is signed correctly, so bring
9858                // over the latest parsed certs.
9859                pkgSetting.signatures.mSignatures = pkg.mSignatures;
9860            } else {
9861                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9862                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9863                            "Package " + pkg.packageName + " upgrade keys do not match the "
9864                                    + "previously installed version");
9865                } else {
9866                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9867                    String msg = "System package " + pkg.packageName
9868                            + " signature changed; retaining data.";
9869                    reportSettingsProblem(Log.WARN, msg);
9870                }
9871            }
9872        } else {
9873            try {
9874                final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
9875                final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
9876                final boolean compatMatch = verifySignatures(signatureCheckPs, pkg.mSignatures,
9877                        compareCompat, compareRecover);
9878                // The new KeySets will be re-added later in the scanning process.
9879                if (compatMatch) {
9880                    synchronized (mPackages) {
9881                        ksms.removeAppKeySetDataLPw(pkg.packageName);
9882                    }
9883                }
9884                // We just determined the app is signed correctly, so bring
9885                // over the latest parsed certs.
9886                pkgSetting.signatures.mSignatures = pkg.mSignatures;
9887            } catch (PackageManagerException e) {
9888                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9889                    throw e;
9890                }
9891                // The signature has changed, but this package is in the system
9892                // image...  let's recover!
9893                pkgSetting.signatures.mSignatures = pkg.mSignatures;
9894                // However...  if this package is part of a shared user, but it
9895                // doesn't match the signature of the shared user, let's fail.
9896                // What this means is that you can't change the signatures
9897                // associated with an overall shared user, which doesn't seem all
9898                // that unreasonable.
9899                if (signatureCheckPs.sharedUser != null) {
9900                    if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
9901                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9902                        throw new PackageManagerException(
9903                                INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9904                                "Signature mismatch for shared user: "
9905                                        + pkgSetting.sharedUser);
9906                    }
9907                }
9908                // File a report about this.
9909                String msg = "System package " + pkg.packageName
9910                        + " signature changed; retaining data.";
9911                reportSettingsProblem(Log.WARN, msg);
9912            }
9913        }
9914
9915        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
9916            // This package wants to adopt ownership of permissions from
9917            // another package.
9918            for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
9919                final String origName = pkg.mAdoptPermissions.get(i);
9920                final PackageSetting orig = mSettings.getPackageLPr(origName);
9921                if (orig != null) {
9922                    if (verifyPackageUpdateLPr(orig, pkg)) {
9923                        Slog.i(TAG, "Adopting permissions from " + origName + " to "
9924                                + pkg.packageName);
9925                        mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
9926                    }
9927                }
9928            }
9929        }
9930
9931        if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
9932            for (int i = changedAbiCodePath.size() - 1; i <= 0; --i) {
9933                final String codePathString = changedAbiCodePath.get(i);
9934                try {
9935                    mInstaller.rmdex(codePathString,
9936                            getDexCodeInstructionSet(getPreferredInstructionSet()));
9937                } catch (InstallerException ignored) {
9938                }
9939            }
9940        }
9941
9942        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9943            if (oldPkgSetting != null) {
9944                synchronized (mPackages) {
9945                    mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting);
9946                }
9947            }
9948        } else {
9949            final int userId = user == null ? 0 : user.getIdentifier();
9950            // Modify state for the given package setting
9951            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
9952                    (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
9953            if (pkgSetting.getInstantApp(userId)) {
9954                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
9955            }
9956        }
9957    }
9958
9959    /**
9960     * Returns the "real" name of the package.
9961     * <p>This may differ from the package's actual name if the application has already
9962     * been installed under one of this package's original names.
9963     */
9964    private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg,
9965            @Nullable String renamedPkgName) {
9966        if (pkg.mOriginalPackages == null || !pkg.mOriginalPackages.contains(renamedPkgName)) {
9967            return null;
9968        }
9969        return pkg.mRealPackage;
9970    }
9971
9972    /**
9973     * Returns the original package setting.
9974     * <p>A package can migrate its name during an update. In this scenario, a package
9975     * designates a set of names that it considers as one of its original names.
9976     * <p>An original package must be signed identically and it must have the same
9977     * shared user [if any].
9978     */
9979    @GuardedBy("mPackages")
9980    private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg,
9981            @Nullable String renamedPkgName) {
9982        if (pkg.mOriginalPackages == null || pkg.mOriginalPackages.contains(renamedPkgName)) {
9983            return null;
9984        }
9985        for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) {
9986            final PackageSetting originalPs =
9987                    mSettings.getPackageLPr(pkg.mOriginalPackages.get(i));
9988            if (originalPs != null) {
9989                // the package is already installed under its original name...
9990                // but, should we use it?
9991                if (!verifyPackageUpdateLPr(originalPs, pkg)) {
9992                    // the new package is incompatible with the original
9993                    continue;
9994                } else if (originalPs.sharedUser != null) {
9995                    if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) {
9996                        // the shared user id is incompatible with the original
9997                        Slog.w(TAG, "Unable to migrate data from " + originalPs.name
9998                                + " to " + pkg.packageName + ": old uid "
9999                                + originalPs.sharedUser.name
10000                                + " differs from " + pkg.mSharedUserId);
10001                        continue;
10002                    }
10003                    // TODO: Add case when shared user id is added [b/28144775]
10004                } else {
10005                    if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10006                            + pkg.packageName + " to old name " + originalPs.name);
10007                }
10008                return originalPs;
10009            }
10010        }
10011        return null;
10012    }
10013
10014    /**
10015     * Renames the package if it was installed under a different name.
10016     * <p>When we've already installed the package under an original name, update
10017     * the new package so we can continue to have the old name.
10018     */
10019    private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg,
10020            @NonNull String renamedPackageName) {
10021        if (pkg.mOriginalPackages == null
10022                || !pkg.mOriginalPackages.contains(renamedPackageName)
10023                || pkg.packageName.equals(renamedPackageName)) {
10024            return;
10025        }
10026        pkg.setPackageName(renamedPackageName);
10027    }
10028
10029    /**
10030     * Just scans the package without any side effects.
10031     * <p>Not entirely true at the moment. There is still one side effect -- this
10032     * method potentially modifies a live {@link PackageSetting} object representing
10033     * the package being scanned. This will be resolved in the future.
10034     *
10035     * @param request Information about the package to be scanned
10036     * @param isUnderFactoryTest Whether or not the device is under factory test
10037     * @param currentTime The current time, in millis
10038     * @return The results of the scan
10039     */
10040    @GuardedBy("mInstallLock")
10041    private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request,
10042            boolean isUnderFactoryTest, long currentTime)
10043                    throws PackageManagerException {
10044        final PackageParser.Package pkg = request.pkg;
10045        PackageSetting pkgSetting = request.pkgSetting;
10046        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10047        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10048        final @ParseFlags int parseFlags = request.parseFlags;
10049        final @ScanFlags int scanFlags = request.scanFlags;
10050        final String realPkgName = request.realPkgName;
10051        final SharedUserSetting sharedUserSetting = request.sharedUserSetting;
10052        final UserHandle user = request.user;
10053        final boolean isPlatformPackage = request.isPlatformPackage;
10054
10055        List<String> changedAbiCodePath = null;
10056
10057        if (DEBUG_PACKAGE_SCANNING) {
10058            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10059                Log.d(TAG, "Scanning package " + pkg.packageName);
10060        }
10061
10062        if (Build.IS_DEBUGGABLE &&
10063                pkg.isPrivileged() &&
10064                !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) {
10065            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10066        }
10067
10068        // Initialize package source and resource directories
10069        final File scanFile = new File(pkg.codePath);
10070        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10071        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10072
10073        // We keep references to the derived CPU Abis from settings in oder to reuse
10074        // them in the case where we're not upgrading or booting for the first time.
10075        String primaryCpuAbiFromSettings = null;
10076        String secondaryCpuAbiFromSettings = null;
10077        boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0;
10078
10079        if (!needToDeriveAbi) {
10080            if (pkgSetting != null) {
10081                primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString;
10082                secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString;
10083            } else {
10084                // Re-scanning a system package after uninstalling updates; need to derive ABI
10085                needToDeriveAbi = true;
10086            }
10087        }
10088
10089        if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) {
10090            PackageManagerService.reportSettingsProblem(Log.WARN,
10091                    "Package " + pkg.packageName + " shared user changed from "
10092                            + (pkgSetting.sharedUser != null
10093                            ? pkgSetting.sharedUser.name : "<nothing>")
10094                            + " to "
10095                            + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>")
10096                            + "; replacing with new");
10097            pkgSetting = null;
10098        }
10099
10100        String[] usesStaticLibraries = null;
10101        if (pkg.usesStaticLibraries != null) {
10102            usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10103            pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10104        }
10105
10106        final boolean createNewPackage = (pkgSetting == null);
10107        if (createNewPackage) {
10108            final String parentPackageName = (pkg.parentPackage != null)
10109                    ? pkg.parentPackage.packageName : null;
10110            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10111            final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10112            // REMOVE SharedUserSetting from method; update in a separate call
10113            pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting,
10114                    disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile,
10115                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
10116                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10117                    pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10118                    user, true /*allowInstall*/, instantApp, virtualPreload,
10119                    parentPackageName, pkg.getChildPackageNames(),
10120                    UserManagerService.getInstance(), usesStaticLibraries,
10121                    pkg.usesStaticLibrariesVersions);
10122        } else {
10123            // REMOVE SharedUserSetting from method; update in a separate call.
10124            //
10125            // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10126            // secondaryCpuAbi are not known at this point so we always update them
10127            // to null here, only to reset them at a later point.
10128            Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting,
10129                    destCodeFile, pkg.applicationInfo.nativeLibraryDir,
10130                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10131                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10132                    pkg.getChildPackageNames(), UserManagerService.getInstance(),
10133                    usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10134        }
10135        if (createNewPackage && originalPkgSetting != null) {
10136            // If we are first transitioning from an original package,
10137            // fix up the new package's name now.  We need to do this after
10138            // looking up the package under its new name, so getPackageLP
10139            // can take care of fiddling things correctly.
10140            pkg.setPackageName(originalPkgSetting.name);
10141
10142            // File a report about this.
10143            String msg = "New package " + pkgSetting.realName
10144                    + " renamed to replace old package " + pkgSetting.name;
10145            reportSettingsProblem(Log.WARN, msg);
10146        }
10147
10148        if (disabledPkgSetting != null) {
10149            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10150        }
10151
10152        SELinuxMMAC.assignSeInfoValue(pkg);
10153
10154        pkg.mExtras = pkgSetting;
10155        pkg.applicationInfo.processName = fixProcessName(
10156                pkg.applicationInfo.packageName,
10157                pkg.applicationInfo.processName);
10158
10159        if (!isPlatformPackage) {
10160            // Get all of our default paths setup
10161            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10162        }
10163
10164        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10165
10166        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10167            if (needToDeriveAbi) {
10168                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10169                final boolean extractNativeLibs = !pkg.isLibrary();
10170                derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs);
10171                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10172
10173                // Some system apps still use directory structure for native libraries
10174                // in which case we might end up not detecting abi solely based on apk
10175                // structure. Try to detect abi based on directory structure.
10176                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10177                        pkg.applicationInfo.primaryCpuAbi == null) {
10178                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10179                    setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10180                }
10181            } else {
10182                // This is not a first boot or an upgrade, don't bother deriving the
10183                // ABI during the scan. Instead, trust the value that was stored in the
10184                // package setting.
10185                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10186                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10187
10188                setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10189
10190                if (DEBUG_ABI_SELECTION) {
10191                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10192                            pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10193                            pkg.applicationInfo.secondaryCpuAbi);
10194                }
10195            }
10196        } else {
10197            if ((scanFlags & SCAN_MOVE) != 0) {
10198                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10199                // but we already have this packages package info in the PackageSetting. We just
10200                // use that and derive the native library path based on the new codepath.
10201                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10202                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10203            }
10204
10205            // Set native library paths again. For moves, the path will be updated based on the
10206            // ABIs we've determined above. For non-moves, the path will be updated based on the
10207            // ABIs we determined during compilation, but the path will depend on the final
10208            // package path (after the rename away from the stage path).
10209            setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10210        }
10211
10212        // This is a special case for the "system" package, where the ABI is
10213        // dictated by the zygote configuration (and init.rc). We should keep track
10214        // of this ABI so that we can deal with "normal" applications that run under
10215        // the same UID correctly.
10216        if (isPlatformPackage) {
10217            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10218                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10219        }
10220
10221        // If there's a mismatch between the abi-override in the package setting
10222        // and the abiOverride specified for the install. Warn about this because we
10223        // would've already compiled the app without taking the package setting into
10224        // account.
10225        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10226            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10227                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10228                        " for package " + pkg.packageName);
10229            }
10230        }
10231
10232        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10233        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10234        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10235
10236        // Copy the derived override back to the parsed package, so that we can
10237        // update the package settings accordingly.
10238        pkg.cpuAbiOverride = cpuAbiOverride;
10239
10240        if (DEBUG_ABI_SELECTION) {
10241            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10242                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10243                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10244        }
10245
10246        // Push the derived path down into PackageSettings so we know what to
10247        // clean up at uninstall time.
10248        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10249
10250        if (DEBUG_ABI_SELECTION) {
10251            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10252                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10253                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10254        }
10255
10256        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10257            // We don't do this here during boot because we can do it all
10258            // at once after scanning all existing packages.
10259            //
10260            // We also do this *before* we perform dexopt on this package, so that
10261            // we can avoid redundant dexopts, and also to make sure we've got the
10262            // code and package path correct.
10263            changedAbiCodePath =
10264                    adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10265        }
10266
10267        if (isUnderFactoryTest && pkg.requestedPermissions.contains(
10268                android.Manifest.permission.FACTORY_TEST)) {
10269            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10270        }
10271
10272        if (isSystemApp(pkg)) {
10273            pkgSetting.isOrphaned = true;
10274        }
10275
10276        // Take care of first install / last update times.
10277        final long scanFileTime = getLastModifiedTime(pkg);
10278        if (currentTime != 0) {
10279            if (pkgSetting.firstInstallTime == 0) {
10280                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10281            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10282                pkgSetting.lastUpdateTime = currentTime;
10283            }
10284        } else if (pkgSetting.firstInstallTime == 0) {
10285            // We need *something*.  Take time time stamp of the file.
10286            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10287        } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10288            if (scanFileTime != pkgSetting.timeStamp) {
10289                // A package on the system image has changed; consider this
10290                // to be an update.
10291                pkgSetting.lastUpdateTime = scanFileTime;
10292            }
10293        }
10294        pkgSetting.setTimeStamp(scanFileTime);
10295
10296        return new ScanResult(true, pkgSetting, changedAbiCodePath);
10297    }
10298
10299    /**
10300     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10301     */
10302    private static boolean apkHasCode(String fileName) {
10303        StrictJarFile jarFile = null;
10304        try {
10305            jarFile = new StrictJarFile(fileName,
10306                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10307            return jarFile.findEntry("classes.dex") != null;
10308        } catch (IOException ignore) {
10309        } finally {
10310            try {
10311                if (jarFile != null) {
10312                    jarFile.close();
10313                }
10314            } catch (IOException ignore) {}
10315        }
10316        return false;
10317    }
10318
10319    /**
10320     * Enforces code policy for the package. This ensures that if an APK has
10321     * declared hasCode="true" in its manifest that the APK actually contains
10322     * code.
10323     *
10324     * @throws PackageManagerException If bytecode could not be found when it should exist
10325     */
10326    private static void assertCodePolicy(PackageParser.Package pkg)
10327            throws PackageManagerException {
10328        final boolean shouldHaveCode =
10329                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10330        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10331            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10332                    "Package " + pkg.baseCodePath + " code is missing");
10333        }
10334
10335        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10336            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10337                final boolean splitShouldHaveCode =
10338                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10339                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10340                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10341                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10342                }
10343            }
10344        }
10345    }
10346
10347    /**
10348     * Applies policy to the parsed package based upon the given policy flags.
10349     * Ensures the package is in a good state.
10350     * <p>
10351     * Implementation detail: This method must NOT have any side effect. It would
10352     * ideally be static, but, it requires locks to read system state.
10353     */
10354    private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10355            final @ScanFlags int scanFlags) {
10356        if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10357            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10358            if (pkg.applicationInfo.isDirectBootAware()) {
10359                // we're direct boot aware; set for all components
10360                for (PackageParser.Service s : pkg.services) {
10361                    s.info.encryptionAware = s.info.directBootAware = true;
10362                }
10363                for (PackageParser.Provider p : pkg.providers) {
10364                    p.info.encryptionAware = p.info.directBootAware = true;
10365                }
10366                for (PackageParser.Activity a : pkg.activities) {
10367                    a.info.encryptionAware = a.info.directBootAware = true;
10368                }
10369                for (PackageParser.Activity r : pkg.receivers) {
10370                    r.info.encryptionAware = r.info.directBootAware = true;
10371                }
10372            }
10373            if (compressedFileExists(pkg.codePath)) {
10374                pkg.isStub = true;
10375            }
10376        } else {
10377            // non system apps can't be flagged as core
10378            pkg.coreApp = false;
10379            // clear flags not applicable to regular apps
10380            pkg.applicationInfo.flags &=
10381                    ~ApplicationInfo.FLAG_PERSISTENT;
10382            pkg.applicationInfo.privateFlags &=
10383                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10384            pkg.applicationInfo.privateFlags &=
10385                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10386            // clear protected broadcasts
10387            pkg.protectedBroadcasts = null;
10388            // cap permission priorities
10389            if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) {
10390                for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) {
10391                    pkg.permissionGroups.get(i).info.priority = 0;
10392                }
10393            }
10394        }
10395        if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10396            // ignore export request for single user receivers
10397            if (pkg.receivers != null) {
10398                for (int i = pkg.receivers.size() - 1; i >= 0; --i) {
10399                    final PackageParser.Activity receiver = pkg.receivers.get(i);
10400                    if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) {
10401                        receiver.info.exported = false;
10402                    }
10403                }
10404            }
10405            // ignore export request for single user services
10406            if (pkg.services != null) {
10407                for (int i = pkg.services.size() - 1; i >= 0; --i) {
10408                    final PackageParser.Service service = pkg.services.get(i);
10409                    if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
10410                        service.info.exported = false;
10411                    }
10412                }
10413            }
10414            // ignore export request for single user providers
10415            if (pkg.providers != null) {
10416                for (int i = pkg.providers.size() - 1; i >= 0; --i) {
10417                    final PackageParser.Provider provider = pkg.providers.get(i);
10418                    if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) {
10419                        provider.info.exported = false;
10420                    }
10421                }
10422            }
10423        }
10424        pkg.mTrustedOverlay = (scanFlags & SCAN_TRUSTED_OVERLAY) != 0;
10425
10426        if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) {
10427            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10428        }
10429
10430        if ((scanFlags & SCAN_AS_OEM) != 0) {
10431            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10432        }
10433
10434        if ((scanFlags & SCAN_AS_VENDOR) != 0) {
10435            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR;
10436        }
10437
10438        if (!isSystemApp(pkg)) {
10439            // Only system apps can use these features.
10440            pkg.mOriginalPackages = null;
10441            pkg.mRealPackage = null;
10442            pkg.mAdoptPermissions = null;
10443        }
10444    }
10445
10446    /**
10447     * Asserts the parsed package is valid according to the given policy. If the
10448     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10449     * <p>
10450     * Implementation detail: This method must NOT have any side effects. It would
10451     * ideally be static, but, it requires locks to read system state.
10452     *
10453     * @throws PackageManagerException If the package fails any of the validation checks
10454     */
10455    private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10456            final @ScanFlags int scanFlags)
10457                    throws PackageManagerException {
10458        if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10459            assertCodePolicy(pkg);
10460        }
10461
10462        if (pkg.applicationInfo.getCodePath() == null ||
10463                pkg.applicationInfo.getResourcePath() == null) {
10464            // Bail out. The resource and code paths haven't been set.
10465            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10466                    "Code and resource paths haven't been set correctly");
10467        }
10468
10469        // Make sure we're not adding any bogus keyset info
10470        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10471        ksms.assertScannedPackageValid(pkg);
10472
10473        synchronized (mPackages) {
10474            // The special "android" package can only be defined once
10475            if (pkg.packageName.equals("android")) {
10476                if (mAndroidApplication != null) {
10477                    Slog.w(TAG, "*************************************************");
10478                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10479                    Slog.w(TAG, " codePath=" + pkg.codePath);
10480                    Slog.w(TAG, "*************************************************");
10481                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10482                            "Core android package being redefined.  Skipping.");
10483                }
10484            }
10485
10486            // A package name must be unique; don't allow duplicates
10487            if (mPackages.containsKey(pkg.packageName)) {
10488                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10489                        "Application package " + pkg.packageName
10490                        + " already installed.  Skipping duplicate.");
10491            }
10492
10493            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10494                // Static libs have a synthetic package name containing the version
10495                // but we still want the base name to be unique.
10496                if (mPackages.containsKey(pkg.manifestPackageName)) {
10497                    throw new PackageManagerException(
10498                            "Duplicate static shared lib provider package");
10499                }
10500
10501                // Static shared libraries should have at least O target SDK
10502                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10503                    throw new PackageManagerException(
10504                            "Packages declaring static-shared libs must target O SDK or higher");
10505                }
10506
10507                // Package declaring static a shared lib cannot be instant apps
10508                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10509                    throw new PackageManagerException(
10510                            "Packages declaring static-shared libs cannot be instant apps");
10511                }
10512
10513                // Package declaring static a shared lib cannot be renamed since the package
10514                // name is synthetic and apps can't code around package manager internals.
10515                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10516                    throw new PackageManagerException(
10517                            "Packages declaring static-shared libs cannot be renamed");
10518                }
10519
10520                // Package declaring static a shared lib cannot declare child packages
10521                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10522                    throw new PackageManagerException(
10523                            "Packages declaring static-shared libs cannot have child packages");
10524                }
10525
10526                // Package declaring static a shared lib cannot declare dynamic libs
10527                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10528                    throw new PackageManagerException(
10529                            "Packages declaring static-shared libs cannot declare dynamic libs");
10530                }
10531
10532                // Package declaring static a shared lib cannot declare shared users
10533                if (pkg.mSharedUserId != null) {
10534                    throw new PackageManagerException(
10535                            "Packages declaring static-shared libs cannot declare shared users");
10536                }
10537
10538                // Static shared libs cannot declare activities
10539                if (!pkg.activities.isEmpty()) {
10540                    throw new PackageManagerException(
10541                            "Static shared libs cannot declare activities");
10542                }
10543
10544                // Static shared libs cannot declare services
10545                if (!pkg.services.isEmpty()) {
10546                    throw new PackageManagerException(
10547                            "Static shared libs cannot declare services");
10548                }
10549
10550                // Static shared libs cannot declare providers
10551                if (!pkg.providers.isEmpty()) {
10552                    throw new PackageManagerException(
10553                            "Static shared libs cannot declare content providers");
10554                }
10555
10556                // Static shared libs cannot declare receivers
10557                if (!pkg.receivers.isEmpty()) {
10558                    throw new PackageManagerException(
10559                            "Static shared libs cannot declare broadcast receivers");
10560                }
10561
10562                // Static shared libs cannot declare permission groups
10563                if (!pkg.permissionGroups.isEmpty()) {
10564                    throw new PackageManagerException(
10565                            "Static shared libs cannot declare permission groups");
10566                }
10567
10568                // Static shared libs cannot declare permissions
10569                if (!pkg.permissions.isEmpty()) {
10570                    throw new PackageManagerException(
10571                            "Static shared libs cannot declare permissions");
10572                }
10573
10574                // Static shared libs cannot declare protected broadcasts
10575                if (pkg.protectedBroadcasts != null) {
10576                    throw new PackageManagerException(
10577                            "Static shared libs cannot declare protected broadcasts");
10578                }
10579
10580                // Static shared libs cannot be overlay targets
10581                if (pkg.mOverlayTarget != null) {
10582                    throw new PackageManagerException(
10583                            "Static shared libs cannot be overlay targets");
10584                }
10585
10586                // The version codes must be ordered as lib versions
10587                long minVersionCode = Long.MIN_VALUE;
10588                long maxVersionCode = Long.MAX_VALUE;
10589
10590                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10591                        pkg.staticSharedLibName);
10592                if (versionedLib != null) {
10593                    final int versionCount = versionedLib.size();
10594                    for (int i = 0; i < versionCount; i++) {
10595                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10596                        final long libVersionCode = libInfo.getDeclaringPackage()
10597                                .getLongVersionCode();
10598                        if (libInfo.getLongVersion() <  pkg.staticSharedLibVersion) {
10599                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10600                        } else if (libInfo.getLongVersion() >  pkg.staticSharedLibVersion) {
10601                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10602                        } else {
10603                            minVersionCode = maxVersionCode = libVersionCode;
10604                            break;
10605                        }
10606                    }
10607                }
10608                if (pkg.getLongVersionCode() < minVersionCode
10609                        || pkg.getLongVersionCode() > maxVersionCode) {
10610                    throw new PackageManagerException("Static shared"
10611                            + " lib version codes must be ordered as lib versions");
10612                }
10613            }
10614
10615            // Only privileged apps and updated privileged apps can add child packages.
10616            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10617                if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10618                    throw new PackageManagerException("Only privileged apps can add child "
10619                            + "packages. Ignoring package " + pkg.packageName);
10620                }
10621                final int childCount = pkg.childPackages.size();
10622                for (int i = 0; i < childCount; i++) {
10623                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10624                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10625                            childPkg.packageName)) {
10626                        throw new PackageManagerException("Can't override child of "
10627                                + "another disabled app. Ignoring package " + pkg.packageName);
10628                    }
10629                }
10630            }
10631
10632            // If we're only installing presumed-existing packages, require that the
10633            // scanned APK is both already known and at the path previously established
10634            // for it.  Previously unknown packages we pick up normally, but if we have an
10635            // a priori expectation about this package's install presence, enforce it.
10636            // With a singular exception for new system packages. When an OTA contains
10637            // a new system package, we allow the codepath to change from a system location
10638            // to the user-installed location. If we don't allow this change, any newer,
10639            // user-installed version of the application will be ignored.
10640            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10641                if (mExpectingBetter.containsKey(pkg.packageName)) {
10642                    logCriticalInfo(Log.WARN,
10643                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10644                } else {
10645                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10646                    if (known != null) {
10647                        if (DEBUG_PACKAGE_SCANNING) {
10648                            Log.d(TAG, "Examining " + pkg.codePath
10649                                    + " and requiring known paths " + known.codePathString
10650                                    + " & " + known.resourcePathString);
10651                        }
10652                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10653                                || !pkg.applicationInfo.getResourcePath().equals(
10654                                        known.resourcePathString)) {
10655                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10656                                    "Application package " + pkg.packageName
10657                                    + " found at " + pkg.applicationInfo.getCodePath()
10658                                    + " but expected at " + known.codePathString
10659                                    + "; ignoring.");
10660                        }
10661                    } else {
10662                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10663                                "Application package " + pkg.packageName
10664                                + " not found; ignoring.");
10665                    }
10666                }
10667            }
10668
10669            // Verify that this new package doesn't have any content providers
10670            // that conflict with existing packages.  Only do this if the
10671            // package isn't already installed, since we don't want to break
10672            // things that are installed.
10673            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10674                final int N = pkg.providers.size();
10675                int i;
10676                for (i=0; i<N; i++) {
10677                    PackageParser.Provider p = pkg.providers.get(i);
10678                    if (p.info.authority != null) {
10679                        String names[] = p.info.authority.split(";");
10680                        for (int j = 0; j < names.length; j++) {
10681                            if (mProvidersByAuthority.containsKey(names[j])) {
10682                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10683                                final String otherPackageName =
10684                                        ((other != null && other.getComponentName() != null) ?
10685                                                other.getComponentName().getPackageName() : "?");
10686                                throw new PackageManagerException(
10687                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10688                                        "Can't install because provider name " + names[j]
10689                                                + " (in package " + pkg.applicationInfo.packageName
10690                                                + ") is already used by " + otherPackageName);
10691                            }
10692                        }
10693                    }
10694                }
10695            }
10696        }
10697    }
10698
10699    private boolean addSharedLibraryLPw(String path, String apk, String name, long version,
10700            int type, String declaringPackageName, long declaringVersionCode) {
10701        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10702        if (versionedLib == null) {
10703            versionedLib = new LongSparseArray<>();
10704            mSharedLibraries.put(name, versionedLib);
10705            if (type == SharedLibraryInfo.TYPE_STATIC) {
10706                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10707            }
10708        } else if (versionedLib.indexOfKey(version) >= 0) {
10709            return false;
10710        }
10711        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
10712                version, type, declaringPackageName, declaringVersionCode);
10713        versionedLib.put(version, libEntry);
10714        return true;
10715    }
10716
10717    private boolean removeSharedLibraryLPw(String name, long version) {
10718        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10719        if (versionedLib == null) {
10720            return false;
10721        }
10722        final int libIdx = versionedLib.indexOfKey(version);
10723        if (libIdx < 0) {
10724            return false;
10725        }
10726        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
10727        versionedLib.remove(version);
10728        if (versionedLib.size() <= 0) {
10729            mSharedLibraries.remove(name);
10730            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
10731                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
10732                        .getPackageName());
10733            }
10734        }
10735        return true;
10736    }
10737
10738    /**
10739     * Adds a scanned package to the system. When this method is finished, the package will
10740     * be available for query, resolution, etc...
10741     */
10742    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
10743            UserHandle user, final @ScanFlags int scanFlags, boolean chatty) {
10744        final String pkgName = pkg.packageName;
10745        if (mCustomResolverComponentName != null &&
10746                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
10747            setUpCustomResolverActivity(pkg);
10748        }
10749
10750        if (pkg.packageName.equals("android")) {
10751            synchronized (mPackages) {
10752                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10753                    // Set up information for our fall-back user intent resolution activity.
10754                    mPlatformPackage = pkg;
10755                    pkg.mVersionCode = mSdkVersion;
10756                    pkg.mVersionCodeMajor = 0;
10757                    mAndroidApplication = pkg.applicationInfo;
10758                    if (!mResolverReplaced) {
10759                        mResolveActivity.applicationInfo = mAndroidApplication;
10760                        mResolveActivity.name = ResolverActivity.class.getName();
10761                        mResolveActivity.packageName = mAndroidApplication.packageName;
10762                        mResolveActivity.processName = "system:ui";
10763                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10764                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
10765                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
10766                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
10767                        mResolveActivity.exported = true;
10768                        mResolveActivity.enabled = true;
10769                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
10770                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
10771                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
10772                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
10773                                | ActivityInfo.CONFIG_ORIENTATION
10774                                | ActivityInfo.CONFIG_KEYBOARD
10775                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
10776                        mResolveInfo.activityInfo = mResolveActivity;
10777                        mResolveInfo.priority = 0;
10778                        mResolveInfo.preferredOrder = 0;
10779                        mResolveInfo.match = 0;
10780                        mResolveComponentName = new ComponentName(
10781                                mAndroidApplication.packageName, mResolveActivity.name);
10782                    }
10783                }
10784            }
10785        }
10786
10787        ArrayList<PackageParser.Package> clientLibPkgs = null;
10788        // writer
10789        synchronized (mPackages) {
10790            boolean hasStaticSharedLibs = false;
10791
10792            // Any app can add new static shared libraries
10793            if (pkg.staticSharedLibName != null) {
10794                // Static shared libs don't allow renaming as they have synthetic package
10795                // names to allow install of multiple versions, so use name from manifest.
10796                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
10797                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
10798                        pkg.manifestPackageName, pkg.getLongVersionCode())) {
10799                    hasStaticSharedLibs = true;
10800                } else {
10801                    Slog.w(TAG, "Package " + pkg.packageName + " library "
10802                                + pkg.staticSharedLibName + " already exists; skipping");
10803                }
10804                // Static shared libs cannot be updated once installed since they
10805                // use synthetic package name which includes the version code, so
10806                // not need to update other packages's shared lib dependencies.
10807            }
10808
10809            if (!hasStaticSharedLibs
10810                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10811                // Only system apps can add new dynamic shared libraries.
10812                if (pkg.libraryNames != null) {
10813                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
10814                        String name = pkg.libraryNames.get(i);
10815                        boolean allowed = false;
10816                        if (pkg.isUpdatedSystemApp()) {
10817                            // New library entries can only be added through the
10818                            // system image.  This is important to get rid of a lot
10819                            // of nasty edge cases: for example if we allowed a non-
10820                            // system update of the app to add a library, then uninstalling
10821                            // the update would make the library go away, and assumptions
10822                            // we made such as through app install filtering would now
10823                            // have allowed apps on the device which aren't compatible
10824                            // with it.  Better to just have the restriction here, be
10825                            // conservative, and create many fewer cases that can negatively
10826                            // impact the user experience.
10827                            final PackageSetting sysPs = mSettings
10828                                    .getDisabledSystemPkgLPr(pkg.packageName);
10829                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
10830                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
10831                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
10832                                        allowed = true;
10833                                        break;
10834                                    }
10835                                }
10836                            }
10837                        } else {
10838                            allowed = true;
10839                        }
10840                        if (allowed) {
10841                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
10842                                    SharedLibraryInfo.VERSION_UNDEFINED,
10843                                    SharedLibraryInfo.TYPE_DYNAMIC,
10844                                    pkg.packageName, pkg.getLongVersionCode())) {
10845                                Slog.w(TAG, "Package " + pkg.packageName + " library "
10846                                        + name + " already exists; skipping");
10847                            }
10848                        } else {
10849                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
10850                                    + name + " that is not declared on system image; skipping");
10851                        }
10852                    }
10853
10854                    if ((scanFlags & SCAN_BOOTING) == 0) {
10855                        // If we are not booting, we need to update any applications
10856                        // that are clients of our shared library.  If we are booting,
10857                        // this will all be done once the scan is complete.
10858                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
10859                    }
10860                }
10861            }
10862        }
10863
10864        if ((scanFlags & SCAN_BOOTING) != 0) {
10865            // No apps can run during boot scan, so they don't need to be frozen
10866        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
10867            // Caller asked to not kill app, so it's probably not frozen
10868        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
10869            // Caller asked us to ignore frozen check for some reason; they
10870            // probably didn't know the package name
10871        } else {
10872            // We're doing major surgery on this package, so it better be frozen
10873            // right now to keep it from launching
10874            checkPackageFrozen(pkgName);
10875        }
10876
10877        // Also need to kill any apps that are dependent on the library.
10878        if (clientLibPkgs != null) {
10879            for (int i=0; i<clientLibPkgs.size(); i++) {
10880                PackageParser.Package clientPkg = clientLibPkgs.get(i);
10881                killApplication(clientPkg.applicationInfo.packageName,
10882                        clientPkg.applicationInfo.uid, "update lib");
10883            }
10884        }
10885
10886        // writer
10887        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
10888
10889        synchronized (mPackages) {
10890            // We don't expect installation to fail beyond this point
10891
10892            // Add the new setting to mSettings
10893            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
10894            // Add the new setting to mPackages
10895            mPackages.put(pkg.applicationInfo.packageName, pkg);
10896            // Make sure we don't accidentally delete its data.
10897            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
10898            while (iter.hasNext()) {
10899                PackageCleanItem item = iter.next();
10900                if (pkgName.equals(item.packageName)) {
10901                    iter.remove();
10902                }
10903            }
10904
10905            // Add the package's KeySets to the global KeySetManagerService
10906            KeySetManagerService ksms = mSettings.mKeySetManagerService;
10907            ksms.addScannedPackageLPw(pkg);
10908
10909            int N = pkg.providers.size();
10910            StringBuilder r = null;
10911            int i;
10912            for (i=0; i<N; i++) {
10913                PackageParser.Provider p = pkg.providers.get(i);
10914                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
10915                        p.info.processName);
10916                mProviders.addProvider(p);
10917                p.syncable = p.info.isSyncable;
10918                if (p.info.authority != null) {
10919                    String names[] = p.info.authority.split(";");
10920                    p.info.authority = null;
10921                    for (int j = 0; j < names.length; j++) {
10922                        if (j == 1 && p.syncable) {
10923                            // We only want the first authority for a provider to possibly be
10924                            // syncable, so if we already added this provider using a different
10925                            // authority clear the syncable flag. We copy the provider before
10926                            // changing it because the mProviders object contains a reference
10927                            // to a provider that we don't want to change.
10928                            // Only do this for the second authority since the resulting provider
10929                            // object can be the same for all future authorities for this provider.
10930                            p = new PackageParser.Provider(p);
10931                            p.syncable = false;
10932                        }
10933                        if (!mProvidersByAuthority.containsKey(names[j])) {
10934                            mProvidersByAuthority.put(names[j], p);
10935                            if (p.info.authority == null) {
10936                                p.info.authority = names[j];
10937                            } else {
10938                                p.info.authority = p.info.authority + ";" + names[j];
10939                            }
10940                            if (DEBUG_PACKAGE_SCANNING) {
10941                                if (chatty)
10942                                    Log.d(TAG, "Registered content provider: " + names[j]
10943                                            + ", className = " + p.info.name + ", isSyncable = "
10944                                            + p.info.isSyncable);
10945                            }
10946                        } else {
10947                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10948                            Slog.w(TAG, "Skipping provider name " + names[j] +
10949                                    " (in package " + pkg.applicationInfo.packageName +
10950                                    "): name already used by "
10951                                    + ((other != null && other.getComponentName() != null)
10952                                            ? other.getComponentName().getPackageName() : "?"));
10953                        }
10954                    }
10955                }
10956                if (chatty) {
10957                    if (r == null) {
10958                        r = new StringBuilder(256);
10959                    } else {
10960                        r.append(' ');
10961                    }
10962                    r.append(p.info.name);
10963                }
10964            }
10965            if (r != null) {
10966                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
10967            }
10968
10969            N = pkg.services.size();
10970            r = null;
10971            for (i=0; i<N; i++) {
10972                PackageParser.Service s = pkg.services.get(i);
10973                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
10974                        s.info.processName);
10975                mServices.addService(s);
10976                if (chatty) {
10977                    if (r == null) {
10978                        r = new StringBuilder(256);
10979                    } else {
10980                        r.append(' ');
10981                    }
10982                    r.append(s.info.name);
10983                }
10984            }
10985            if (r != null) {
10986                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
10987            }
10988
10989            N = pkg.receivers.size();
10990            r = null;
10991            for (i=0; i<N; i++) {
10992                PackageParser.Activity a = pkg.receivers.get(i);
10993                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10994                        a.info.processName);
10995                mReceivers.addActivity(a, "receiver");
10996                if (chatty) {
10997                    if (r == null) {
10998                        r = new StringBuilder(256);
10999                    } else {
11000                        r.append(' ');
11001                    }
11002                    r.append(a.info.name);
11003                }
11004            }
11005            if (r != null) {
11006                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11007            }
11008
11009            N = pkg.activities.size();
11010            r = null;
11011            for (i=0; i<N; i++) {
11012                PackageParser.Activity a = pkg.activities.get(i);
11013                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11014                        a.info.processName);
11015                mActivities.addActivity(a, "activity");
11016                if (chatty) {
11017                    if (r == null) {
11018                        r = new StringBuilder(256);
11019                    } else {
11020                        r.append(' ');
11021                    }
11022                    r.append(a.info.name);
11023                }
11024            }
11025            if (r != null) {
11026                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11027            }
11028
11029            // Don't allow ephemeral applications to define new permissions groups.
11030            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11031                Slog.w(TAG, "Permission groups from package " + pkg.packageName
11032                        + " ignored: instant apps cannot define new permission groups.");
11033            } else {
11034                mPermissionManager.addAllPermissionGroups(pkg, chatty);
11035            }
11036
11037            // Don't allow ephemeral applications to define new permissions.
11038            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11039                Slog.w(TAG, "Permissions from package " + pkg.packageName
11040                        + " ignored: instant apps cannot define new permissions.");
11041            } else {
11042                mPermissionManager.addAllPermissions(pkg, chatty);
11043            }
11044
11045            N = pkg.instrumentation.size();
11046            r = null;
11047            for (i=0; i<N; i++) {
11048                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11049                a.info.packageName = pkg.applicationInfo.packageName;
11050                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11051                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11052                a.info.splitNames = pkg.splitNames;
11053                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11054                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11055                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11056                a.info.dataDir = pkg.applicationInfo.dataDir;
11057                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11058                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11059                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11060                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11061                mInstrumentation.put(a.getComponentName(), a);
11062                if (chatty) {
11063                    if (r == null) {
11064                        r = new StringBuilder(256);
11065                    } else {
11066                        r.append(' ');
11067                    }
11068                    r.append(a.info.name);
11069                }
11070            }
11071            if (r != null) {
11072                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11073            }
11074
11075            if (pkg.protectedBroadcasts != null) {
11076                N = pkg.protectedBroadcasts.size();
11077                synchronized (mProtectedBroadcasts) {
11078                    for (i = 0; i < N; i++) {
11079                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11080                    }
11081                }
11082            }
11083        }
11084
11085        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11086    }
11087
11088    /**
11089     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11090     * is derived purely on the basis of the contents of {@code scanFile} and
11091     * {@code cpuAbiOverride}.
11092     *
11093     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11094     */
11095    private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride,
11096            boolean extractLibs)
11097                    throws PackageManagerException {
11098        // Give ourselves some initial paths; we'll come back for another
11099        // pass once we've determined ABI below.
11100        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11101
11102        // We would never need to extract libs for forward-locked and external packages,
11103        // since the container service will do it for us. We shouldn't attempt to
11104        // extract libs from system app when it was not updated.
11105        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11106                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11107            extractLibs = false;
11108        }
11109
11110        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11111        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11112
11113        NativeLibraryHelper.Handle handle = null;
11114        try {
11115            handle = NativeLibraryHelper.Handle.create(pkg);
11116            // TODO(multiArch): This can be null for apps that didn't go through the
11117            // usual installation process. We can calculate it again, like we
11118            // do during install time.
11119            //
11120            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11121            // unnecessary.
11122            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11123
11124            // Null out the abis so that they can be recalculated.
11125            pkg.applicationInfo.primaryCpuAbi = null;
11126            pkg.applicationInfo.secondaryCpuAbi = null;
11127            if (isMultiArch(pkg.applicationInfo)) {
11128                // Warn if we've set an abiOverride for multi-lib packages..
11129                // By definition, we need to copy both 32 and 64 bit libraries for
11130                // such packages.
11131                if (pkg.cpuAbiOverride != null
11132                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11133                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11134                }
11135
11136                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11137                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11138                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11139                    if (extractLibs) {
11140                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11141                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11142                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11143                                useIsaSpecificSubdirs);
11144                    } else {
11145                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11146                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11147                    }
11148                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11149                }
11150
11151                // Shared library native code should be in the APK zip aligned
11152                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11153                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11154                            "Shared library native lib extraction not supported");
11155                }
11156
11157                maybeThrowExceptionForMultiArchCopy(
11158                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11159
11160                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11161                    if (extractLibs) {
11162                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11163                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11164                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11165                                useIsaSpecificSubdirs);
11166                    } else {
11167                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11168                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11169                    }
11170                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11171                }
11172
11173                maybeThrowExceptionForMultiArchCopy(
11174                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11175
11176                if (abi64 >= 0) {
11177                    // Shared library native libs should be in the APK zip aligned
11178                    if (extractLibs && pkg.isLibrary()) {
11179                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11180                                "Shared library native lib extraction not supported");
11181                    }
11182                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11183                }
11184
11185                if (abi32 >= 0) {
11186                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11187                    if (abi64 >= 0) {
11188                        if (pkg.use32bitAbi) {
11189                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11190                            pkg.applicationInfo.primaryCpuAbi = abi;
11191                        } else {
11192                            pkg.applicationInfo.secondaryCpuAbi = abi;
11193                        }
11194                    } else {
11195                        pkg.applicationInfo.primaryCpuAbi = abi;
11196                    }
11197                }
11198            } else {
11199                String[] abiList = (cpuAbiOverride != null) ?
11200                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11201
11202                // Enable gross and lame hacks for apps that are built with old
11203                // SDK tools. We must scan their APKs for renderscript bitcode and
11204                // not launch them if it's present. Don't bother checking on devices
11205                // that don't have 64 bit support.
11206                boolean needsRenderScriptOverride = false;
11207                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11208                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11209                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11210                    needsRenderScriptOverride = true;
11211                }
11212
11213                final int copyRet;
11214                if (extractLibs) {
11215                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11216                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11217                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11218                } else {
11219                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11220                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11221                }
11222                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11223
11224                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11225                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11226                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11227                }
11228
11229                if (copyRet >= 0) {
11230                    // Shared libraries that have native libs must be multi-architecture
11231                    if (pkg.isLibrary()) {
11232                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11233                                "Shared library with native libs must be multiarch");
11234                    }
11235                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11236                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11237                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11238                } else if (needsRenderScriptOverride) {
11239                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11240                }
11241            }
11242        } catch (IOException ioe) {
11243            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11244        } finally {
11245            IoUtils.closeQuietly(handle);
11246        }
11247
11248        // Now that we've calculated the ABIs and determined if it's an internal app,
11249        // we will go ahead and populate the nativeLibraryPath.
11250        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11251    }
11252
11253    /**
11254     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11255     * i.e, so that all packages can be run inside a single process if required.
11256     *
11257     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11258     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11259     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11260     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11261     * updating a package that belongs to a shared user.
11262     *
11263     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11264     * adds unnecessary complexity.
11265     */
11266    private static @Nullable List<String> adjustCpuAbisForSharedUserLPw(
11267            Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) {
11268        List<String> changedAbiCodePath = null;
11269        String requiredInstructionSet = null;
11270        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11271            requiredInstructionSet = VMRuntime.getInstructionSet(
11272                     scannedPackage.applicationInfo.primaryCpuAbi);
11273        }
11274
11275        PackageSetting requirer = null;
11276        for (PackageSetting ps : packagesForUser) {
11277            // If packagesForUser contains scannedPackage, we skip it. This will happen
11278            // when scannedPackage is an update of an existing package. Without this check,
11279            // we will never be able to change the ABI of any package belonging to a shared
11280            // user, even if it's compatible with other packages.
11281            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11282                if (ps.primaryCpuAbiString == null) {
11283                    continue;
11284                }
11285
11286                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11287                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11288                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11289                    // this but there's not much we can do.
11290                    String errorMessage = "Instruction set mismatch, "
11291                            + ((requirer == null) ? "[caller]" : requirer)
11292                            + " requires " + requiredInstructionSet + " whereas " + ps
11293                            + " requires " + instructionSet;
11294                    Slog.w(TAG, errorMessage);
11295                }
11296
11297                if (requiredInstructionSet == null) {
11298                    requiredInstructionSet = instructionSet;
11299                    requirer = ps;
11300                }
11301            }
11302        }
11303
11304        if (requiredInstructionSet != null) {
11305            String adjustedAbi;
11306            if (requirer != null) {
11307                // requirer != null implies that either scannedPackage was null or that scannedPackage
11308                // did not require an ABI, in which case we have to adjust scannedPackage to match
11309                // the ABI of the set (which is the same as requirer's ABI)
11310                adjustedAbi = requirer.primaryCpuAbiString;
11311                if (scannedPackage != null) {
11312                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11313                }
11314            } else {
11315                // requirer == null implies that we're updating all ABIs in the set to
11316                // match scannedPackage.
11317                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11318            }
11319
11320            for (PackageSetting ps : packagesForUser) {
11321                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11322                    if (ps.primaryCpuAbiString != null) {
11323                        continue;
11324                    }
11325
11326                    ps.primaryCpuAbiString = adjustedAbi;
11327                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11328                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11329                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11330                        if (DEBUG_ABI_SELECTION) {
11331                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11332                                    + " (requirer="
11333                                    + (requirer != null ? requirer.pkg : "null")
11334                                    + ", scannedPackage="
11335                                    + (scannedPackage != null ? scannedPackage : "null")
11336                                    + ")");
11337                        }
11338                        if (changedAbiCodePath == null) {
11339                            changedAbiCodePath = new ArrayList<>();
11340                        }
11341                        changedAbiCodePath.add(ps.codePathString);
11342                    }
11343                }
11344            }
11345        }
11346        return changedAbiCodePath;
11347    }
11348
11349    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11350        synchronized (mPackages) {
11351            mResolverReplaced = true;
11352            // Set up information for custom user intent resolution activity.
11353            mResolveActivity.applicationInfo = pkg.applicationInfo;
11354            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11355            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11356            mResolveActivity.processName = pkg.applicationInfo.packageName;
11357            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11358            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11359                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11360            mResolveActivity.theme = 0;
11361            mResolveActivity.exported = true;
11362            mResolveActivity.enabled = true;
11363            mResolveInfo.activityInfo = mResolveActivity;
11364            mResolveInfo.priority = 0;
11365            mResolveInfo.preferredOrder = 0;
11366            mResolveInfo.match = 0;
11367            mResolveComponentName = mCustomResolverComponentName;
11368            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11369                    mResolveComponentName);
11370        }
11371    }
11372
11373    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11374        if (installerActivity == null) {
11375            if (DEBUG_EPHEMERAL) {
11376                Slog.d(TAG, "Clear ephemeral installer activity");
11377            }
11378            mInstantAppInstallerActivity = null;
11379            return;
11380        }
11381
11382        if (DEBUG_EPHEMERAL) {
11383            Slog.d(TAG, "Set ephemeral installer activity: "
11384                    + installerActivity.getComponentName());
11385        }
11386        // Set up information for ephemeral installer activity
11387        mInstantAppInstallerActivity = installerActivity;
11388        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11389                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11390        mInstantAppInstallerActivity.exported = true;
11391        mInstantAppInstallerActivity.enabled = true;
11392        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11393        mInstantAppInstallerInfo.priority = 0;
11394        mInstantAppInstallerInfo.preferredOrder = 1;
11395        mInstantAppInstallerInfo.isDefault = true;
11396        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11397                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11398    }
11399
11400    private static String calculateBundledApkRoot(final String codePathString) {
11401        final File codePath = new File(codePathString);
11402        final File codeRoot;
11403        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11404            codeRoot = Environment.getRootDirectory();
11405        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11406            codeRoot = Environment.getOemDirectory();
11407        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11408            codeRoot = Environment.getVendorDirectory();
11409        } else {
11410            // Unrecognized code path; take its top real segment as the apk root:
11411            // e.g. /something/app/blah.apk => /something
11412            try {
11413                File f = codePath.getCanonicalFile();
11414                File parent = f.getParentFile();    // non-null because codePath is a file
11415                File tmp;
11416                while ((tmp = parent.getParentFile()) != null) {
11417                    f = parent;
11418                    parent = tmp;
11419                }
11420                codeRoot = f;
11421                Slog.w(TAG, "Unrecognized code path "
11422                        + codePath + " - using " + codeRoot);
11423            } catch (IOException e) {
11424                // Can't canonicalize the code path -- shenanigans?
11425                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11426                return Environment.getRootDirectory().getPath();
11427            }
11428        }
11429        return codeRoot.getPath();
11430    }
11431
11432    /**
11433     * Derive and set the location of native libraries for the given package,
11434     * which varies depending on where and how the package was installed.
11435     */
11436    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11437        final ApplicationInfo info = pkg.applicationInfo;
11438        final String codePath = pkg.codePath;
11439        final File codeFile = new File(codePath);
11440        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11441        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11442
11443        info.nativeLibraryRootDir = null;
11444        info.nativeLibraryRootRequiresIsa = false;
11445        info.nativeLibraryDir = null;
11446        info.secondaryNativeLibraryDir = null;
11447
11448        if (isApkFile(codeFile)) {
11449            // Monolithic install
11450            if (bundledApp) {
11451                // If "/system/lib64/apkname" exists, assume that is the per-package
11452                // native library directory to use; otherwise use "/system/lib/apkname".
11453                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11454                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11455                        getPrimaryInstructionSet(info));
11456
11457                // This is a bundled system app so choose the path based on the ABI.
11458                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11459                // is just the default path.
11460                final String apkName = deriveCodePathName(codePath);
11461                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11462                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11463                        apkName).getAbsolutePath();
11464
11465                if (info.secondaryCpuAbi != null) {
11466                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11467                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11468                            secondaryLibDir, apkName).getAbsolutePath();
11469                }
11470            } else if (asecApp) {
11471                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11472                        .getAbsolutePath();
11473            } else {
11474                final String apkName = deriveCodePathName(codePath);
11475                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11476                        .getAbsolutePath();
11477            }
11478
11479            info.nativeLibraryRootRequiresIsa = false;
11480            info.nativeLibraryDir = info.nativeLibraryRootDir;
11481        } else {
11482            // Cluster install
11483            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11484            info.nativeLibraryRootRequiresIsa = true;
11485
11486            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11487                    getPrimaryInstructionSet(info)).getAbsolutePath();
11488
11489            if (info.secondaryCpuAbi != null) {
11490                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11491                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11492            }
11493        }
11494    }
11495
11496    /**
11497     * Calculate the abis and roots for a bundled app. These can uniquely
11498     * be determined from the contents of the system partition, i.e whether
11499     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11500     * of this information, and instead assume that the system was built
11501     * sensibly.
11502     */
11503    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11504                                           PackageSetting pkgSetting) {
11505        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11506
11507        // If "/system/lib64/apkname" exists, assume that is the per-package
11508        // native library directory to use; otherwise use "/system/lib/apkname".
11509        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11510        setBundledAppAbi(pkg, apkRoot, apkName);
11511        // pkgSetting might be null during rescan following uninstall of updates
11512        // to a bundled app, so accommodate that possibility.  The settings in
11513        // that case will be established later from the parsed package.
11514        //
11515        // If the settings aren't null, sync them up with what we've just derived.
11516        // note that apkRoot isn't stored in the package settings.
11517        if (pkgSetting != null) {
11518            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11519            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11520        }
11521    }
11522
11523    /**
11524     * Deduces the ABI of a bundled app and sets the relevant fields on the
11525     * parsed pkg object.
11526     *
11527     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11528     *        under which system libraries are installed.
11529     * @param apkName the name of the installed package.
11530     */
11531    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11532        final File codeFile = new File(pkg.codePath);
11533
11534        final boolean has64BitLibs;
11535        final boolean has32BitLibs;
11536        if (isApkFile(codeFile)) {
11537            // Monolithic install
11538            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11539            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11540        } else {
11541            // Cluster install
11542            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11543            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11544                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11545                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11546                has64BitLibs = (new File(rootDir, isa)).exists();
11547            } else {
11548                has64BitLibs = false;
11549            }
11550            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11551                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11552                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11553                has32BitLibs = (new File(rootDir, isa)).exists();
11554            } else {
11555                has32BitLibs = false;
11556            }
11557        }
11558
11559        if (has64BitLibs && !has32BitLibs) {
11560            // The package has 64 bit libs, but not 32 bit libs. Its primary
11561            // ABI should be 64 bit. We can safely assume here that the bundled
11562            // native libraries correspond to the most preferred ABI in the list.
11563
11564            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11565            pkg.applicationInfo.secondaryCpuAbi = null;
11566        } else if (has32BitLibs && !has64BitLibs) {
11567            // The package has 32 bit libs but not 64 bit libs. Its primary
11568            // ABI should be 32 bit.
11569
11570            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11571            pkg.applicationInfo.secondaryCpuAbi = null;
11572        } else if (has32BitLibs && has64BitLibs) {
11573            // The application has both 64 and 32 bit bundled libraries. We check
11574            // here that the app declares multiArch support, and warn if it doesn't.
11575            //
11576            // We will be lenient here and record both ABIs. The primary will be the
11577            // ABI that's higher on the list, i.e, a device that's configured to prefer
11578            // 64 bit apps will see a 64 bit primary ABI,
11579
11580            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11581                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11582            }
11583
11584            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11585                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11586                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11587            } else {
11588                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11589                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11590            }
11591        } else {
11592            pkg.applicationInfo.primaryCpuAbi = null;
11593            pkg.applicationInfo.secondaryCpuAbi = null;
11594        }
11595    }
11596
11597    private void killApplication(String pkgName, int appId, String reason) {
11598        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11599    }
11600
11601    private void killApplication(String pkgName, int appId, int userId, String reason) {
11602        // Request the ActivityManager to kill the process(only for existing packages)
11603        // so that we do not end up in a confused state while the user is still using the older
11604        // version of the application while the new one gets installed.
11605        final long token = Binder.clearCallingIdentity();
11606        try {
11607            IActivityManager am = ActivityManager.getService();
11608            if (am != null) {
11609                try {
11610                    am.killApplication(pkgName, appId, userId, reason);
11611                } catch (RemoteException e) {
11612                }
11613            }
11614        } finally {
11615            Binder.restoreCallingIdentity(token);
11616        }
11617    }
11618
11619    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11620        // Remove the parent package setting
11621        PackageSetting ps = (PackageSetting) pkg.mExtras;
11622        if (ps != null) {
11623            removePackageLI(ps, chatty);
11624        }
11625        // Remove the child package setting
11626        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11627        for (int i = 0; i < childCount; i++) {
11628            PackageParser.Package childPkg = pkg.childPackages.get(i);
11629            ps = (PackageSetting) childPkg.mExtras;
11630            if (ps != null) {
11631                removePackageLI(ps, chatty);
11632            }
11633        }
11634    }
11635
11636    void removePackageLI(PackageSetting ps, boolean chatty) {
11637        if (DEBUG_INSTALL) {
11638            if (chatty)
11639                Log.d(TAG, "Removing package " + ps.name);
11640        }
11641
11642        // writer
11643        synchronized (mPackages) {
11644            mPackages.remove(ps.name);
11645            final PackageParser.Package pkg = ps.pkg;
11646            if (pkg != null) {
11647                cleanPackageDataStructuresLILPw(pkg, chatty);
11648            }
11649        }
11650    }
11651
11652    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11653        if (DEBUG_INSTALL) {
11654            if (chatty)
11655                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11656        }
11657
11658        // writer
11659        synchronized (mPackages) {
11660            // Remove the parent package
11661            mPackages.remove(pkg.applicationInfo.packageName);
11662            cleanPackageDataStructuresLILPw(pkg, chatty);
11663
11664            // Remove the child packages
11665            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11666            for (int i = 0; i < childCount; i++) {
11667                PackageParser.Package childPkg = pkg.childPackages.get(i);
11668                mPackages.remove(childPkg.applicationInfo.packageName);
11669                cleanPackageDataStructuresLILPw(childPkg, chatty);
11670            }
11671        }
11672    }
11673
11674    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
11675        int N = pkg.providers.size();
11676        StringBuilder r = null;
11677        int i;
11678        for (i=0; i<N; i++) {
11679            PackageParser.Provider p = pkg.providers.get(i);
11680            mProviders.removeProvider(p);
11681            if (p.info.authority == null) {
11682
11683                /* There was another ContentProvider with this authority when
11684                 * this app was installed so this authority is null,
11685                 * Ignore it as we don't have to unregister the provider.
11686                 */
11687                continue;
11688            }
11689            String names[] = p.info.authority.split(";");
11690            for (int j = 0; j < names.length; j++) {
11691                if (mProvidersByAuthority.get(names[j]) == p) {
11692                    mProvidersByAuthority.remove(names[j]);
11693                    if (DEBUG_REMOVE) {
11694                        if (chatty)
11695                            Log.d(TAG, "Unregistered content provider: " + names[j]
11696                                    + ", className = " + p.info.name + ", isSyncable = "
11697                                    + p.info.isSyncable);
11698                    }
11699                }
11700            }
11701            if (DEBUG_REMOVE && chatty) {
11702                if (r == null) {
11703                    r = new StringBuilder(256);
11704                } else {
11705                    r.append(' ');
11706                }
11707                r.append(p.info.name);
11708            }
11709        }
11710        if (r != null) {
11711            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
11712        }
11713
11714        N = pkg.services.size();
11715        r = null;
11716        for (i=0; i<N; i++) {
11717            PackageParser.Service s = pkg.services.get(i);
11718            mServices.removeService(s);
11719            if (chatty) {
11720                if (r == null) {
11721                    r = new StringBuilder(256);
11722                } else {
11723                    r.append(' ');
11724                }
11725                r.append(s.info.name);
11726            }
11727        }
11728        if (r != null) {
11729            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
11730        }
11731
11732        N = pkg.receivers.size();
11733        r = null;
11734        for (i=0; i<N; i++) {
11735            PackageParser.Activity a = pkg.receivers.get(i);
11736            mReceivers.removeActivity(a, "receiver");
11737            if (DEBUG_REMOVE && chatty) {
11738                if (r == null) {
11739                    r = new StringBuilder(256);
11740                } else {
11741                    r.append(' ');
11742                }
11743                r.append(a.info.name);
11744            }
11745        }
11746        if (r != null) {
11747            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
11748        }
11749
11750        N = pkg.activities.size();
11751        r = null;
11752        for (i=0; i<N; i++) {
11753            PackageParser.Activity a = pkg.activities.get(i);
11754            mActivities.removeActivity(a, "activity");
11755            if (DEBUG_REMOVE && chatty) {
11756                if (r == null) {
11757                    r = new StringBuilder(256);
11758                } else {
11759                    r.append(' ');
11760                }
11761                r.append(a.info.name);
11762            }
11763        }
11764        if (r != null) {
11765            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11766        }
11767
11768        mPermissionManager.removeAllPermissions(pkg, chatty);
11769
11770        N = pkg.instrumentation.size();
11771        r = null;
11772        for (i=0; i<N; i++) {
11773            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11774            mInstrumentation.remove(a.getComponentName());
11775            if (DEBUG_REMOVE && chatty) {
11776                if (r == null) {
11777                    r = new StringBuilder(256);
11778                } else {
11779                    r.append(' ');
11780                }
11781                r.append(a.info.name);
11782            }
11783        }
11784        if (r != null) {
11785            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11786        }
11787
11788        r = null;
11789        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11790            // Only system apps can hold shared libraries.
11791            if (pkg.libraryNames != null) {
11792                for (i = 0; i < pkg.libraryNames.size(); i++) {
11793                    String name = pkg.libraryNames.get(i);
11794                    if (removeSharedLibraryLPw(name, 0)) {
11795                        if (DEBUG_REMOVE && chatty) {
11796                            if (r == null) {
11797                                r = new StringBuilder(256);
11798                            } else {
11799                                r.append(' ');
11800                            }
11801                            r.append(name);
11802                        }
11803                    }
11804                }
11805            }
11806        }
11807
11808        r = null;
11809
11810        // Any package can hold static shared libraries.
11811        if (pkg.staticSharedLibName != null) {
11812            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11813                if (DEBUG_REMOVE && chatty) {
11814                    if (r == null) {
11815                        r = new StringBuilder(256);
11816                    } else {
11817                        r.append(' ');
11818                    }
11819                    r.append(pkg.staticSharedLibName);
11820                }
11821            }
11822        }
11823
11824        if (r != null) {
11825            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11826        }
11827    }
11828
11829
11830    final class ActivityIntentResolver
11831            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
11832        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11833                boolean defaultOnly, int userId) {
11834            if (!sUserManager.exists(userId)) return null;
11835            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
11836            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11837        }
11838
11839        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11840                int userId) {
11841            if (!sUserManager.exists(userId)) return null;
11842            mFlags = flags;
11843            return super.queryIntent(intent, resolvedType,
11844                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11845                    userId);
11846        }
11847
11848        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11849                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
11850            if (!sUserManager.exists(userId)) return null;
11851            if (packageActivities == null) {
11852                return null;
11853            }
11854            mFlags = flags;
11855            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11856            final int N = packageActivities.size();
11857            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
11858                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
11859
11860            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
11861            for (int i = 0; i < N; ++i) {
11862                intentFilters = packageActivities.get(i).intents;
11863                if (intentFilters != null && intentFilters.size() > 0) {
11864                    PackageParser.ActivityIntentInfo[] array =
11865                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
11866                    intentFilters.toArray(array);
11867                    listCut.add(array);
11868                }
11869            }
11870            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11871        }
11872
11873        /**
11874         * Finds a privileged activity that matches the specified activity names.
11875         */
11876        private PackageParser.Activity findMatchingActivity(
11877                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
11878            for (PackageParser.Activity sysActivity : activityList) {
11879                if (sysActivity.info.name.equals(activityInfo.name)) {
11880                    return sysActivity;
11881                }
11882                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
11883                    return sysActivity;
11884                }
11885                if (sysActivity.info.targetActivity != null) {
11886                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
11887                        return sysActivity;
11888                    }
11889                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
11890                        return sysActivity;
11891                    }
11892                }
11893            }
11894            return null;
11895        }
11896
11897        public class IterGenerator<E> {
11898            public Iterator<E> generate(ActivityIntentInfo info) {
11899                return null;
11900            }
11901        }
11902
11903        public class ActionIterGenerator extends IterGenerator<String> {
11904            @Override
11905            public Iterator<String> generate(ActivityIntentInfo info) {
11906                return info.actionsIterator();
11907            }
11908        }
11909
11910        public class CategoriesIterGenerator extends IterGenerator<String> {
11911            @Override
11912            public Iterator<String> generate(ActivityIntentInfo info) {
11913                return info.categoriesIterator();
11914            }
11915        }
11916
11917        public class SchemesIterGenerator extends IterGenerator<String> {
11918            @Override
11919            public Iterator<String> generate(ActivityIntentInfo info) {
11920                return info.schemesIterator();
11921            }
11922        }
11923
11924        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
11925            @Override
11926            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
11927                return info.authoritiesIterator();
11928            }
11929        }
11930
11931        /**
11932         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
11933         * MODIFIED. Do not pass in a list that should not be changed.
11934         */
11935        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
11936                IterGenerator<T> generator, Iterator<T> searchIterator) {
11937            // loop through the set of actions; every one must be found in the intent filter
11938            while (searchIterator.hasNext()) {
11939                // we must have at least one filter in the list to consider a match
11940                if (intentList.size() == 0) {
11941                    break;
11942                }
11943
11944                final T searchAction = searchIterator.next();
11945
11946                // loop through the set of intent filters
11947                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
11948                while (intentIter.hasNext()) {
11949                    final ActivityIntentInfo intentInfo = intentIter.next();
11950                    boolean selectionFound = false;
11951
11952                    // loop through the intent filter's selection criteria; at least one
11953                    // of them must match the searched criteria
11954                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
11955                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
11956                        final T intentSelection = intentSelectionIter.next();
11957                        if (intentSelection != null && intentSelection.equals(searchAction)) {
11958                            selectionFound = true;
11959                            break;
11960                        }
11961                    }
11962
11963                    // the selection criteria wasn't found in this filter's set; this filter
11964                    // is not a potential match
11965                    if (!selectionFound) {
11966                        intentIter.remove();
11967                    }
11968                }
11969            }
11970        }
11971
11972        private boolean isProtectedAction(ActivityIntentInfo filter) {
11973            final Iterator<String> actionsIter = filter.actionsIterator();
11974            while (actionsIter != null && actionsIter.hasNext()) {
11975                final String filterAction = actionsIter.next();
11976                if (PROTECTED_ACTIONS.contains(filterAction)) {
11977                    return true;
11978                }
11979            }
11980            return false;
11981        }
11982
11983        /**
11984         * Adjusts the priority of the given intent filter according to policy.
11985         * <p>
11986         * <ul>
11987         * <li>The priority for non privileged applications is capped to '0'</li>
11988         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
11989         * <li>The priority for unbundled updates to privileged applications is capped to the
11990         *      priority defined on the system partition</li>
11991         * </ul>
11992         * <p>
11993         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
11994         * allowed to obtain any priority on any action.
11995         */
11996        private void adjustPriority(
11997                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
11998            // nothing to do; priority is fine as-is
11999            if (intent.getPriority() <= 0) {
12000                return;
12001            }
12002
12003            final ActivityInfo activityInfo = intent.activity.info;
12004            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12005
12006            final boolean privilegedApp =
12007                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12008            if (!privilegedApp) {
12009                // non-privileged applications can never define a priority >0
12010                if (DEBUG_FILTERS) {
12011                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12012                            + " package: " + applicationInfo.packageName
12013                            + " activity: " + intent.activity.className
12014                            + " origPrio: " + intent.getPriority());
12015                }
12016                intent.setPriority(0);
12017                return;
12018            }
12019
12020            if (systemActivities == null) {
12021                // the system package is not disabled; we're parsing the system partition
12022                if (isProtectedAction(intent)) {
12023                    if (mDeferProtectedFilters) {
12024                        // We can't deal with these just yet. No component should ever obtain a
12025                        // >0 priority for a protected actions, with ONE exception -- the setup
12026                        // wizard. The setup wizard, however, cannot be known until we're able to
12027                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12028                        // until all intent filters have been processed. Chicken, meet egg.
12029                        // Let the filter temporarily have a high priority and rectify the
12030                        // priorities after all system packages have been scanned.
12031                        mProtectedFilters.add(intent);
12032                        if (DEBUG_FILTERS) {
12033                            Slog.i(TAG, "Protected action; save for later;"
12034                                    + " package: " + applicationInfo.packageName
12035                                    + " activity: " + intent.activity.className
12036                                    + " origPrio: " + intent.getPriority());
12037                        }
12038                        return;
12039                    } else {
12040                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12041                            Slog.i(TAG, "No setup wizard;"
12042                                + " All protected intents capped to priority 0");
12043                        }
12044                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12045                            if (DEBUG_FILTERS) {
12046                                Slog.i(TAG, "Found setup wizard;"
12047                                    + " allow priority " + intent.getPriority() + ";"
12048                                    + " package: " + intent.activity.info.packageName
12049                                    + " activity: " + intent.activity.className
12050                                    + " priority: " + intent.getPriority());
12051                            }
12052                            // setup wizard gets whatever it wants
12053                            return;
12054                        }
12055                        if (DEBUG_FILTERS) {
12056                            Slog.i(TAG, "Protected action; cap priority to 0;"
12057                                    + " package: " + intent.activity.info.packageName
12058                                    + " activity: " + intent.activity.className
12059                                    + " origPrio: " + intent.getPriority());
12060                        }
12061                        intent.setPriority(0);
12062                        return;
12063                    }
12064                }
12065                // privileged apps on the system image get whatever priority they request
12066                return;
12067            }
12068
12069            // privileged app unbundled update ... try to find the same activity
12070            final PackageParser.Activity foundActivity =
12071                    findMatchingActivity(systemActivities, activityInfo);
12072            if (foundActivity == null) {
12073                // this is a new activity; it cannot obtain >0 priority
12074                if (DEBUG_FILTERS) {
12075                    Slog.i(TAG, "New activity; cap priority to 0;"
12076                            + " package: " + applicationInfo.packageName
12077                            + " activity: " + intent.activity.className
12078                            + " origPrio: " + intent.getPriority());
12079                }
12080                intent.setPriority(0);
12081                return;
12082            }
12083
12084            // found activity, now check for filter equivalence
12085
12086            // a shallow copy is enough; we modify the list, not its contents
12087            final List<ActivityIntentInfo> intentListCopy =
12088                    new ArrayList<>(foundActivity.intents);
12089            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12090
12091            // find matching action subsets
12092            final Iterator<String> actionsIterator = intent.actionsIterator();
12093            if (actionsIterator != null) {
12094                getIntentListSubset(
12095                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12096                if (intentListCopy.size() == 0) {
12097                    // no more intents to match; we're not equivalent
12098                    if (DEBUG_FILTERS) {
12099                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12100                                + " package: " + applicationInfo.packageName
12101                                + " activity: " + intent.activity.className
12102                                + " origPrio: " + intent.getPriority());
12103                    }
12104                    intent.setPriority(0);
12105                    return;
12106                }
12107            }
12108
12109            // find matching category subsets
12110            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12111            if (categoriesIterator != null) {
12112                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12113                        categoriesIterator);
12114                if (intentListCopy.size() == 0) {
12115                    // no more intents to match; we're not equivalent
12116                    if (DEBUG_FILTERS) {
12117                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12118                                + " package: " + applicationInfo.packageName
12119                                + " activity: " + intent.activity.className
12120                                + " origPrio: " + intent.getPriority());
12121                    }
12122                    intent.setPriority(0);
12123                    return;
12124                }
12125            }
12126
12127            // find matching schemes subsets
12128            final Iterator<String> schemesIterator = intent.schemesIterator();
12129            if (schemesIterator != null) {
12130                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12131                        schemesIterator);
12132                if (intentListCopy.size() == 0) {
12133                    // no more intents to match; we're not equivalent
12134                    if (DEBUG_FILTERS) {
12135                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12136                                + " package: " + applicationInfo.packageName
12137                                + " activity: " + intent.activity.className
12138                                + " origPrio: " + intent.getPriority());
12139                    }
12140                    intent.setPriority(0);
12141                    return;
12142                }
12143            }
12144
12145            // find matching authorities subsets
12146            final Iterator<IntentFilter.AuthorityEntry>
12147                    authoritiesIterator = intent.authoritiesIterator();
12148            if (authoritiesIterator != null) {
12149                getIntentListSubset(intentListCopy,
12150                        new AuthoritiesIterGenerator(),
12151                        authoritiesIterator);
12152                if (intentListCopy.size() == 0) {
12153                    // no more intents to match; we're not equivalent
12154                    if (DEBUG_FILTERS) {
12155                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12156                                + " package: " + applicationInfo.packageName
12157                                + " activity: " + intent.activity.className
12158                                + " origPrio: " + intent.getPriority());
12159                    }
12160                    intent.setPriority(0);
12161                    return;
12162                }
12163            }
12164
12165            // we found matching filter(s); app gets the max priority of all intents
12166            int cappedPriority = 0;
12167            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12168                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12169            }
12170            if (intent.getPriority() > cappedPriority) {
12171                if (DEBUG_FILTERS) {
12172                    Slog.i(TAG, "Found matching filter(s);"
12173                            + " cap priority to " + cappedPriority + ";"
12174                            + " package: " + applicationInfo.packageName
12175                            + " activity: " + intent.activity.className
12176                            + " origPrio: " + intent.getPriority());
12177                }
12178                intent.setPriority(cappedPriority);
12179                return;
12180            }
12181            // all this for nothing; the requested priority was <= what was on the system
12182        }
12183
12184        public final void addActivity(PackageParser.Activity a, String type) {
12185            mActivities.put(a.getComponentName(), a);
12186            if (DEBUG_SHOW_INFO)
12187                Log.v(
12188                TAG, "  " + type + " " +
12189                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12190            if (DEBUG_SHOW_INFO)
12191                Log.v(TAG, "    Class=" + a.info.name);
12192            final int NI = a.intents.size();
12193            for (int j=0; j<NI; j++) {
12194                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12195                if ("activity".equals(type)) {
12196                    final PackageSetting ps =
12197                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12198                    final List<PackageParser.Activity> systemActivities =
12199                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12200                    adjustPriority(systemActivities, intent);
12201                }
12202                if (DEBUG_SHOW_INFO) {
12203                    Log.v(TAG, "    IntentFilter:");
12204                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12205                }
12206                if (!intent.debugCheck()) {
12207                    Log.w(TAG, "==> For Activity " + a.info.name);
12208                }
12209                addFilter(intent);
12210            }
12211        }
12212
12213        public final void removeActivity(PackageParser.Activity a, String type) {
12214            mActivities.remove(a.getComponentName());
12215            if (DEBUG_SHOW_INFO) {
12216                Log.v(TAG, "  " + type + " "
12217                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12218                                : a.info.name) + ":");
12219                Log.v(TAG, "    Class=" + a.info.name);
12220            }
12221            final int NI = a.intents.size();
12222            for (int j=0; j<NI; j++) {
12223                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12224                if (DEBUG_SHOW_INFO) {
12225                    Log.v(TAG, "    IntentFilter:");
12226                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12227                }
12228                removeFilter(intent);
12229            }
12230        }
12231
12232        @Override
12233        protected boolean allowFilterResult(
12234                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12235            ActivityInfo filterAi = filter.activity.info;
12236            for (int i=dest.size()-1; i>=0; i--) {
12237                ActivityInfo destAi = dest.get(i).activityInfo;
12238                if (destAi.name == filterAi.name
12239                        && destAi.packageName == filterAi.packageName) {
12240                    return false;
12241                }
12242            }
12243            return true;
12244        }
12245
12246        @Override
12247        protected ActivityIntentInfo[] newArray(int size) {
12248            return new ActivityIntentInfo[size];
12249        }
12250
12251        @Override
12252        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12253            if (!sUserManager.exists(userId)) return true;
12254            PackageParser.Package p = filter.activity.owner;
12255            if (p != null) {
12256                PackageSetting ps = (PackageSetting)p.mExtras;
12257                if (ps != null) {
12258                    // System apps are never considered stopped for purposes of
12259                    // filtering, because there may be no way for the user to
12260                    // actually re-launch them.
12261                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12262                            && ps.getStopped(userId);
12263                }
12264            }
12265            return false;
12266        }
12267
12268        @Override
12269        protected boolean isPackageForFilter(String packageName,
12270                PackageParser.ActivityIntentInfo info) {
12271            return packageName.equals(info.activity.owner.packageName);
12272        }
12273
12274        @Override
12275        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12276                int match, int userId) {
12277            if (!sUserManager.exists(userId)) return null;
12278            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12279                return null;
12280            }
12281            final PackageParser.Activity activity = info.activity;
12282            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12283            if (ps == null) {
12284                return null;
12285            }
12286            final PackageUserState userState = ps.readUserState(userId);
12287            ActivityInfo ai =
12288                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
12289            if (ai == null) {
12290                return null;
12291            }
12292            final boolean matchExplicitlyVisibleOnly =
12293                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12294            final boolean matchVisibleToInstantApp =
12295                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12296            final boolean componentVisible =
12297                    matchVisibleToInstantApp
12298                    && info.isVisibleToInstantApp()
12299                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12300            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12301            // throw out filters that aren't visible to ephemeral apps
12302            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12303                return null;
12304            }
12305            // throw out instant app filters if we're not explicitly requesting them
12306            if (!matchInstantApp && userState.instantApp) {
12307                return null;
12308            }
12309            // throw out instant app filters if updates are available; will trigger
12310            // instant app resolution
12311            if (userState.instantApp && ps.isUpdateAvailable()) {
12312                return null;
12313            }
12314            final ResolveInfo res = new ResolveInfo();
12315            res.activityInfo = ai;
12316            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12317                res.filter = info;
12318            }
12319            if (info != null) {
12320                res.handleAllWebDataURI = info.handleAllWebDataURI();
12321            }
12322            res.priority = info.getPriority();
12323            res.preferredOrder = activity.owner.mPreferredOrder;
12324            //System.out.println("Result: " + res.activityInfo.className +
12325            //                   " = " + res.priority);
12326            res.match = match;
12327            res.isDefault = info.hasDefault;
12328            res.labelRes = info.labelRes;
12329            res.nonLocalizedLabel = info.nonLocalizedLabel;
12330            if (userNeedsBadging(userId)) {
12331                res.noResourceId = true;
12332            } else {
12333                res.icon = info.icon;
12334            }
12335            res.iconResourceId = info.icon;
12336            res.system = res.activityInfo.applicationInfo.isSystemApp();
12337            res.isInstantAppAvailable = userState.instantApp;
12338            return res;
12339        }
12340
12341        @Override
12342        protected void sortResults(List<ResolveInfo> results) {
12343            Collections.sort(results, mResolvePrioritySorter);
12344        }
12345
12346        @Override
12347        protected void dumpFilter(PrintWriter out, String prefix,
12348                PackageParser.ActivityIntentInfo filter) {
12349            out.print(prefix); out.print(
12350                    Integer.toHexString(System.identityHashCode(filter.activity)));
12351                    out.print(' ');
12352                    filter.activity.printComponentShortName(out);
12353                    out.print(" filter ");
12354                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12355        }
12356
12357        @Override
12358        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12359            return filter.activity;
12360        }
12361
12362        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12363            PackageParser.Activity activity = (PackageParser.Activity)label;
12364            out.print(prefix); out.print(
12365                    Integer.toHexString(System.identityHashCode(activity)));
12366                    out.print(' ');
12367                    activity.printComponentShortName(out);
12368            if (count > 1) {
12369                out.print(" ("); out.print(count); out.print(" filters)");
12370            }
12371            out.println();
12372        }
12373
12374        // Keys are String (activity class name), values are Activity.
12375        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12376                = new ArrayMap<ComponentName, PackageParser.Activity>();
12377        private int mFlags;
12378    }
12379
12380    private final class ServiceIntentResolver
12381            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12382        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12383                boolean defaultOnly, int userId) {
12384            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12385            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12386        }
12387
12388        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12389                int userId) {
12390            if (!sUserManager.exists(userId)) return null;
12391            mFlags = flags;
12392            return super.queryIntent(intent, resolvedType,
12393                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12394                    userId);
12395        }
12396
12397        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12398                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12399            if (!sUserManager.exists(userId)) return null;
12400            if (packageServices == null) {
12401                return null;
12402            }
12403            mFlags = flags;
12404            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12405            final int N = packageServices.size();
12406            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12407                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12408
12409            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12410            for (int i = 0; i < N; ++i) {
12411                intentFilters = packageServices.get(i).intents;
12412                if (intentFilters != null && intentFilters.size() > 0) {
12413                    PackageParser.ServiceIntentInfo[] array =
12414                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12415                    intentFilters.toArray(array);
12416                    listCut.add(array);
12417                }
12418            }
12419            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12420        }
12421
12422        public final void addService(PackageParser.Service s) {
12423            mServices.put(s.getComponentName(), s);
12424            if (DEBUG_SHOW_INFO) {
12425                Log.v(TAG, "  "
12426                        + (s.info.nonLocalizedLabel != null
12427                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12428                Log.v(TAG, "    Class=" + s.info.name);
12429            }
12430            final int NI = s.intents.size();
12431            int j;
12432            for (j=0; j<NI; j++) {
12433                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12434                if (DEBUG_SHOW_INFO) {
12435                    Log.v(TAG, "    IntentFilter:");
12436                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12437                }
12438                if (!intent.debugCheck()) {
12439                    Log.w(TAG, "==> For Service " + s.info.name);
12440                }
12441                addFilter(intent);
12442            }
12443        }
12444
12445        public final void removeService(PackageParser.Service s) {
12446            mServices.remove(s.getComponentName());
12447            if (DEBUG_SHOW_INFO) {
12448                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12449                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12450                Log.v(TAG, "    Class=" + s.info.name);
12451            }
12452            final int NI = s.intents.size();
12453            int j;
12454            for (j=0; j<NI; j++) {
12455                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12456                if (DEBUG_SHOW_INFO) {
12457                    Log.v(TAG, "    IntentFilter:");
12458                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12459                }
12460                removeFilter(intent);
12461            }
12462        }
12463
12464        @Override
12465        protected boolean allowFilterResult(
12466                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12467            ServiceInfo filterSi = filter.service.info;
12468            for (int i=dest.size()-1; i>=0; i--) {
12469                ServiceInfo destAi = dest.get(i).serviceInfo;
12470                if (destAi.name == filterSi.name
12471                        && destAi.packageName == filterSi.packageName) {
12472                    return false;
12473                }
12474            }
12475            return true;
12476        }
12477
12478        @Override
12479        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12480            return new PackageParser.ServiceIntentInfo[size];
12481        }
12482
12483        @Override
12484        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12485            if (!sUserManager.exists(userId)) return true;
12486            PackageParser.Package p = filter.service.owner;
12487            if (p != null) {
12488                PackageSetting ps = (PackageSetting)p.mExtras;
12489                if (ps != null) {
12490                    // System apps are never considered stopped for purposes of
12491                    // filtering, because there may be no way for the user to
12492                    // actually re-launch them.
12493                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12494                            && ps.getStopped(userId);
12495                }
12496            }
12497            return false;
12498        }
12499
12500        @Override
12501        protected boolean isPackageForFilter(String packageName,
12502                PackageParser.ServiceIntentInfo info) {
12503            return packageName.equals(info.service.owner.packageName);
12504        }
12505
12506        @Override
12507        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12508                int match, int userId) {
12509            if (!sUserManager.exists(userId)) return null;
12510            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12511            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12512                return null;
12513            }
12514            final PackageParser.Service service = info.service;
12515            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12516            if (ps == null) {
12517                return null;
12518            }
12519            final PackageUserState userState = ps.readUserState(userId);
12520            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12521                    userState, userId);
12522            if (si == null) {
12523                return null;
12524            }
12525            final boolean matchVisibleToInstantApp =
12526                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12527            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12528            // throw out filters that aren't visible to ephemeral apps
12529            if (matchVisibleToInstantApp
12530                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12531                return null;
12532            }
12533            // throw out ephemeral filters if we're not explicitly requesting them
12534            if (!isInstantApp && userState.instantApp) {
12535                return null;
12536            }
12537            // throw out instant app filters if updates are available; will trigger
12538            // instant app resolution
12539            if (userState.instantApp && ps.isUpdateAvailable()) {
12540                return null;
12541            }
12542            final ResolveInfo res = new ResolveInfo();
12543            res.serviceInfo = si;
12544            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12545                res.filter = filter;
12546            }
12547            res.priority = info.getPriority();
12548            res.preferredOrder = service.owner.mPreferredOrder;
12549            res.match = match;
12550            res.isDefault = info.hasDefault;
12551            res.labelRes = info.labelRes;
12552            res.nonLocalizedLabel = info.nonLocalizedLabel;
12553            res.icon = info.icon;
12554            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12555            return res;
12556        }
12557
12558        @Override
12559        protected void sortResults(List<ResolveInfo> results) {
12560            Collections.sort(results, mResolvePrioritySorter);
12561        }
12562
12563        @Override
12564        protected void dumpFilter(PrintWriter out, String prefix,
12565                PackageParser.ServiceIntentInfo filter) {
12566            out.print(prefix); out.print(
12567                    Integer.toHexString(System.identityHashCode(filter.service)));
12568                    out.print(' ');
12569                    filter.service.printComponentShortName(out);
12570                    out.print(" filter ");
12571                    out.print(Integer.toHexString(System.identityHashCode(filter)));
12572                    if (filter.service.info.permission != null) {
12573                        out.print(" permission "); out.println(filter.service.info.permission);
12574                    } else {
12575                        out.println();
12576                    }
12577        }
12578
12579        @Override
12580        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12581            return filter.service;
12582        }
12583
12584        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12585            PackageParser.Service service = (PackageParser.Service)label;
12586            out.print(prefix); out.print(
12587                    Integer.toHexString(System.identityHashCode(service)));
12588                    out.print(' ');
12589                    service.printComponentShortName(out);
12590            if (count > 1) {
12591                out.print(" ("); out.print(count); out.print(" filters)");
12592            }
12593            out.println();
12594        }
12595
12596//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12597//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12598//            final List<ResolveInfo> retList = Lists.newArrayList();
12599//            while (i.hasNext()) {
12600//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12601//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12602//                    retList.add(resolveInfo);
12603//                }
12604//            }
12605//            return retList;
12606//        }
12607
12608        // Keys are String (activity class name), values are Activity.
12609        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12610                = new ArrayMap<ComponentName, PackageParser.Service>();
12611        private int mFlags;
12612    }
12613
12614    private final class ProviderIntentResolver
12615            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12616        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12617                boolean defaultOnly, int userId) {
12618            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12619            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12620        }
12621
12622        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12623                int userId) {
12624            if (!sUserManager.exists(userId))
12625                return null;
12626            mFlags = flags;
12627            return super.queryIntent(intent, resolvedType,
12628                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12629                    userId);
12630        }
12631
12632        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12633                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12634            if (!sUserManager.exists(userId))
12635                return null;
12636            if (packageProviders == null) {
12637                return null;
12638            }
12639            mFlags = flags;
12640            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12641            final int N = packageProviders.size();
12642            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12643                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12644
12645            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12646            for (int i = 0; i < N; ++i) {
12647                intentFilters = packageProviders.get(i).intents;
12648                if (intentFilters != null && intentFilters.size() > 0) {
12649                    PackageParser.ProviderIntentInfo[] array =
12650                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12651                    intentFilters.toArray(array);
12652                    listCut.add(array);
12653                }
12654            }
12655            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12656        }
12657
12658        public final void addProvider(PackageParser.Provider p) {
12659            if (mProviders.containsKey(p.getComponentName())) {
12660                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12661                return;
12662            }
12663
12664            mProviders.put(p.getComponentName(), p);
12665            if (DEBUG_SHOW_INFO) {
12666                Log.v(TAG, "  "
12667                        + (p.info.nonLocalizedLabel != null
12668                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12669                Log.v(TAG, "    Class=" + p.info.name);
12670            }
12671            final int NI = p.intents.size();
12672            int j;
12673            for (j = 0; j < NI; j++) {
12674                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12675                if (DEBUG_SHOW_INFO) {
12676                    Log.v(TAG, "    IntentFilter:");
12677                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12678                }
12679                if (!intent.debugCheck()) {
12680                    Log.w(TAG, "==> For Provider " + p.info.name);
12681                }
12682                addFilter(intent);
12683            }
12684        }
12685
12686        public final void removeProvider(PackageParser.Provider p) {
12687            mProviders.remove(p.getComponentName());
12688            if (DEBUG_SHOW_INFO) {
12689                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
12690                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
12691                Log.v(TAG, "    Class=" + p.info.name);
12692            }
12693            final int NI = p.intents.size();
12694            int j;
12695            for (j = 0; j < NI; j++) {
12696                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12697                if (DEBUG_SHOW_INFO) {
12698                    Log.v(TAG, "    IntentFilter:");
12699                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12700                }
12701                removeFilter(intent);
12702            }
12703        }
12704
12705        @Override
12706        protected boolean allowFilterResult(
12707                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
12708            ProviderInfo filterPi = filter.provider.info;
12709            for (int i = dest.size() - 1; i >= 0; i--) {
12710                ProviderInfo destPi = dest.get(i).providerInfo;
12711                if (destPi.name == filterPi.name
12712                        && destPi.packageName == filterPi.packageName) {
12713                    return false;
12714                }
12715            }
12716            return true;
12717        }
12718
12719        @Override
12720        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
12721            return new PackageParser.ProviderIntentInfo[size];
12722        }
12723
12724        @Override
12725        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
12726            if (!sUserManager.exists(userId))
12727                return true;
12728            PackageParser.Package p = filter.provider.owner;
12729            if (p != null) {
12730                PackageSetting ps = (PackageSetting) p.mExtras;
12731                if (ps != null) {
12732                    // System apps are never considered stopped for purposes of
12733                    // filtering, because there may be no way for the user to
12734                    // actually re-launch them.
12735                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12736                            && ps.getStopped(userId);
12737                }
12738            }
12739            return false;
12740        }
12741
12742        @Override
12743        protected boolean isPackageForFilter(String packageName,
12744                PackageParser.ProviderIntentInfo info) {
12745            return packageName.equals(info.provider.owner.packageName);
12746        }
12747
12748        @Override
12749        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
12750                int match, int userId) {
12751            if (!sUserManager.exists(userId))
12752                return null;
12753            final PackageParser.ProviderIntentInfo info = filter;
12754            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
12755                return null;
12756            }
12757            final PackageParser.Provider provider = info.provider;
12758            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
12759            if (ps == null) {
12760                return null;
12761            }
12762            final PackageUserState userState = ps.readUserState(userId);
12763            final boolean matchVisibleToInstantApp =
12764                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12765            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12766            // throw out filters that aren't visible to instant applications
12767            if (matchVisibleToInstantApp
12768                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12769                return null;
12770            }
12771            // throw out instant application filters if we're not explicitly requesting them
12772            if (!isInstantApp && userState.instantApp) {
12773                return null;
12774            }
12775            // throw out instant application filters if updates are available; will trigger
12776            // instant application resolution
12777            if (userState.instantApp && ps.isUpdateAvailable()) {
12778                return null;
12779            }
12780            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
12781                    userState, userId);
12782            if (pi == null) {
12783                return null;
12784            }
12785            final ResolveInfo res = new ResolveInfo();
12786            res.providerInfo = pi;
12787            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
12788                res.filter = filter;
12789            }
12790            res.priority = info.getPriority();
12791            res.preferredOrder = provider.owner.mPreferredOrder;
12792            res.match = match;
12793            res.isDefault = info.hasDefault;
12794            res.labelRes = info.labelRes;
12795            res.nonLocalizedLabel = info.nonLocalizedLabel;
12796            res.icon = info.icon;
12797            res.system = res.providerInfo.applicationInfo.isSystemApp();
12798            return res;
12799        }
12800
12801        @Override
12802        protected void sortResults(List<ResolveInfo> results) {
12803            Collections.sort(results, mResolvePrioritySorter);
12804        }
12805
12806        @Override
12807        protected void dumpFilter(PrintWriter out, String prefix,
12808                PackageParser.ProviderIntentInfo filter) {
12809            out.print(prefix);
12810            out.print(
12811                    Integer.toHexString(System.identityHashCode(filter.provider)));
12812            out.print(' ');
12813            filter.provider.printComponentShortName(out);
12814            out.print(" filter ");
12815            out.println(Integer.toHexString(System.identityHashCode(filter)));
12816        }
12817
12818        @Override
12819        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
12820            return filter.provider;
12821        }
12822
12823        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12824            PackageParser.Provider provider = (PackageParser.Provider)label;
12825            out.print(prefix); out.print(
12826                    Integer.toHexString(System.identityHashCode(provider)));
12827                    out.print(' ');
12828                    provider.printComponentShortName(out);
12829            if (count > 1) {
12830                out.print(" ("); out.print(count); out.print(" filters)");
12831            }
12832            out.println();
12833        }
12834
12835        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
12836                = new ArrayMap<ComponentName, PackageParser.Provider>();
12837        private int mFlags;
12838    }
12839
12840    static final class EphemeralIntentResolver
12841            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
12842        /**
12843         * The result that has the highest defined order. Ordering applies on a
12844         * per-package basis. Mapping is from package name to Pair of order and
12845         * EphemeralResolveInfo.
12846         * <p>
12847         * NOTE: This is implemented as a field variable for convenience and efficiency.
12848         * By having a field variable, we're able to track filter ordering as soon as
12849         * a non-zero order is defined. Otherwise, multiple loops across the result set
12850         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
12851         * this needs to be contained entirely within {@link #filterResults}.
12852         */
12853        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
12854
12855        @Override
12856        protected AuxiliaryResolveInfo[] newArray(int size) {
12857            return new AuxiliaryResolveInfo[size];
12858        }
12859
12860        @Override
12861        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
12862            return true;
12863        }
12864
12865        @Override
12866        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
12867                int userId) {
12868            if (!sUserManager.exists(userId)) {
12869                return null;
12870            }
12871            final String packageName = responseObj.resolveInfo.getPackageName();
12872            final Integer order = responseObj.getOrder();
12873            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
12874                    mOrderResult.get(packageName);
12875            // ordering is enabled and this item's order isn't high enough
12876            if (lastOrderResult != null && lastOrderResult.first >= order) {
12877                return null;
12878            }
12879            final InstantAppResolveInfo res = responseObj.resolveInfo;
12880            if (order > 0) {
12881                // non-zero order, enable ordering
12882                mOrderResult.put(packageName, new Pair<>(order, res));
12883            }
12884            return responseObj;
12885        }
12886
12887        @Override
12888        protected void filterResults(List<AuxiliaryResolveInfo> results) {
12889            // only do work if ordering is enabled [most of the time it won't be]
12890            if (mOrderResult.size() == 0) {
12891                return;
12892            }
12893            int resultSize = results.size();
12894            for (int i = 0; i < resultSize; i++) {
12895                final InstantAppResolveInfo info = results.get(i).resolveInfo;
12896                final String packageName = info.getPackageName();
12897                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
12898                if (savedInfo == null) {
12899                    // package doesn't having ordering
12900                    continue;
12901                }
12902                if (savedInfo.second == info) {
12903                    // circled back to the highest ordered item; remove from order list
12904                    mOrderResult.remove(packageName);
12905                    if (mOrderResult.size() == 0) {
12906                        // no more ordered items
12907                        break;
12908                    }
12909                    continue;
12910                }
12911                // item has a worse order, remove it from the result list
12912                results.remove(i);
12913                resultSize--;
12914                i--;
12915            }
12916        }
12917    }
12918
12919    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
12920            new Comparator<ResolveInfo>() {
12921        public int compare(ResolveInfo r1, ResolveInfo r2) {
12922            int v1 = r1.priority;
12923            int v2 = r2.priority;
12924            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
12925            if (v1 != v2) {
12926                return (v1 > v2) ? -1 : 1;
12927            }
12928            v1 = r1.preferredOrder;
12929            v2 = r2.preferredOrder;
12930            if (v1 != v2) {
12931                return (v1 > v2) ? -1 : 1;
12932            }
12933            if (r1.isDefault != r2.isDefault) {
12934                return r1.isDefault ? -1 : 1;
12935            }
12936            v1 = r1.match;
12937            v2 = r2.match;
12938            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
12939            if (v1 != v2) {
12940                return (v1 > v2) ? -1 : 1;
12941            }
12942            if (r1.system != r2.system) {
12943                return r1.system ? -1 : 1;
12944            }
12945            if (r1.activityInfo != null) {
12946                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
12947            }
12948            if (r1.serviceInfo != null) {
12949                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
12950            }
12951            if (r1.providerInfo != null) {
12952                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
12953            }
12954            return 0;
12955        }
12956    };
12957
12958    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
12959            new Comparator<ProviderInfo>() {
12960        public int compare(ProviderInfo p1, ProviderInfo p2) {
12961            final int v1 = p1.initOrder;
12962            final int v2 = p2.initOrder;
12963            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
12964        }
12965    };
12966
12967    @Override
12968    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
12969            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
12970            final int[] userIds, int[] instantUserIds) {
12971        mHandler.post(new Runnable() {
12972            @Override
12973            public void run() {
12974                try {
12975                    final IActivityManager am = ActivityManager.getService();
12976                    if (am == null) return;
12977                    final int[] resolvedUserIds;
12978                    if (userIds == null) {
12979                        resolvedUserIds = am.getRunningUserIds();
12980                    } else {
12981                        resolvedUserIds = userIds;
12982                    }
12983                    doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
12984                            resolvedUserIds, false);
12985                    if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) {
12986                        doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
12987                                instantUserIds, true);
12988                    }
12989                } catch (RemoteException ex) {
12990                }
12991            }
12992        });
12993    }
12994
12995    @Override
12996    public void notifyPackageAdded(String packageName) {
12997        final PackageListObserver[] observers;
12998        synchronized (mPackages) {
12999            if (mPackageListObservers.size() == 0) {
13000                return;
13001            }
13002            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13003        }
13004        for (int i = observers.length - 1; i >= 0; --i) {
13005            observers[i].onPackageAdded(packageName);
13006        }
13007    }
13008
13009    @Override
13010    public void notifyPackageRemoved(String packageName) {
13011        final PackageListObserver[] observers;
13012        synchronized (mPackages) {
13013            if (mPackageListObservers.size() == 0) {
13014                return;
13015            }
13016            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13017        }
13018        for (int i = observers.length - 1; i >= 0; --i) {
13019            observers[i].onPackageRemoved(packageName);
13020        }
13021    }
13022
13023    /**
13024     * Sends a broadcast for the given action.
13025     * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with
13026     * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows
13027     * the system and applications allowed to see instant applications to receive package
13028     * lifecycle events for instant applications.
13029     */
13030    private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras,
13031            int flags, String targetPkg, IIntentReceiver finishedReceiver,
13032            int[] userIds, boolean isInstantApp)
13033                    throws RemoteException {
13034        for (int id : userIds) {
13035            final Intent intent = new Intent(action,
13036                    pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13037            final String[] requiredPermissions =
13038                    isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null;
13039            if (extras != null) {
13040                intent.putExtras(extras);
13041            }
13042            if (targetPkg != null) {
13043                intent.setPackage(targetPkg);
13044            }
13045            // Modify the UID when posting to other users
13046            int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13047            if (uid > 0 && UserHandle.getUserId(uid) != id) {
13048                uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13049                intent.putExtra(Intent.EXTRA_UID, uid);
13050            }
13051            intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13052            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13053            if (DEBUG_BROADCASTS) {
13054                RuntimeException here = new RuntimeException("here");
13055                here.fillInStackTrace();
13056                Slog.d(TAG, "Sending to user " + id + ": "
13057                        + intent.toShortString(false, true, false, false)
13058                        + " " + intent.getExtras(), here);
13059            }
13060            am.broadcastIntent(null, intent, null, finishedReceiver,
13061                    0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE,
13062                    null, finishedReceiver != null, false, id);
13063        }
13064    }
13065
13066    /**
13067     * Check if the external storage media is available. This is true if there
13068     * is a mounted external storage medium or if the external storage is
13069     * emulated.
13070     */
13071    private boolean isExternalMediaAvailable() {
13072        return mMediaMounted || Environment.isExternalStorageEmulated();
13073    }
13074
13075    @Override
13076    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13077        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13078            return null;
13079        }
13080        if (!isExternalMediaAvailable()) {
13081                // If the external storage is no longer mounted at this point,
13082                // the caller may not have been able to delete all of this
13083                // packages files and can not delete any more.  Bail.
13084            return null;
13085        }
13086        synchronized (mPackages) {
13087            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13088            if (lastPackage != null) {
13089                pkgs.remove(lastPackage);
13090            }
13091            if (pkgs.size() > 0) {
13092                return pkgs.get(0);
13093            }
13094        }
13095        return null;
13096    }
13097
13098    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13099        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13100                userId, andCode ? 1 : 0, packageName);
13101        if (mSystemReady) {
13102            msg.sendToTarget();
13103        } else {
13104            if (mPostSystemReadyMessages == null) {
13105                mPostSystemReadyMessages = new ArrayList<>();
13106            }
13107            mPostSystemReadyMessages.add(msg);
13108        }
13109    }
13110
13111    void startCleaningPackages() {
13112        // reader
13113        if (!isExternalMediaAvailable()) {
13114            return;
13115        }
13116        synchronized (mPackages) {
13117            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13118                return;
13119            }
13120        }
13121        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13122        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13123        IActivityManager am = ActivityManager.getService();
13124        if (am != null) {
13125            int dcsUid = -1;
13126            synchronized (mPackages) {
13127                if (!mDefaultContainerWhitelisted) {
13128                    mDefaultContainerWhitelisted = true;
13129                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13130                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13131                }
13132            }
13133            try {
13134                if (dcsUid > 0) {
13135                    am.backgroundWhitelistUid(dcsUid);
13136                }
13137                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13138                        UserHandle.USER_SYSTEM);
13139            } catch (RemoteException e) {
13140            }
13141        }
13142    }
13143
13144    @Override
13145    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
13146            int installFlags, String installerPackageName, int userId) {
13147        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
13148
13149        final int callingUid = Binder.getCallingUid();
13150        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13151                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
13152
13153        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13154            try {
13155                if (observer != null) {
13156                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
13157                }
13158            } catch (RemoteException re) {
13159            }
13160            return;
13161        }
13162
13163        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
13164            installFlags |= PackageManager.INSTALL_FROM_ADB;
13165
13166        } else {
13167            // Caller holds INSTALL_PACKAGES permission, so we're less strict
13168            // about installerPackageName.
13169
13170            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
13171            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
13172        }
13173
13174        UserHandle user;
13175        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
13176            user = UserHandle.ALL;
13177        } else {
13178            user = new UserHandle(userId);
13179        }
13180
13181        // Only system components can circumvent runtime permissions when installing.
13182        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
13183                && mContext.checkCallingOrSelfPermission(Manifest.permission
13184                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
13185            throw new SecurityException("You need the "
13186                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
13187                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
13188        }
13189
13190        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
13191                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13192            throw new IllegalArgumentException(
13193                    "New installs into ASEC containers no longer supported");
13194        }
13195
13196        final File originFile = new File(originPath);
13197        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
13198
13199        final Message msg = mHandler.obtainMessage(INIT_COPY);
13200        final VerificationInfo verificationInfo = new VerificationInfo(
13201                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
13202        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
13203                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
13204                null /*packageAbiOverride*/, null /*grantedPermissions*/,
13205                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
13206        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
13207        msg.obj = params;
13208
13209        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
13210                System.identityHashCode(msg.obj));
13211        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13212                System.identityHashCode(msg.obj));
13213
13214        mHandler.sendMessage(msg);
13215    }
13216
13217
13218    /**
13219     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13220     * it is acting on behalf on an enterprise or the user).
13221     *
13222     * Note that the ordering of the conditionals in this method is important. The checks we perform
13223     * are as follows, in this order:
13224     *
13225     * 1) If the install is being performed by a system app, we can trust the app to have set the
13226     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13227     *    what it is.
13228     * 2) If the install is being performed by a device or profile owner app, the install reason
13229     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13230     *    set the install reason correctly. If the app targets an older SDK version where install
13231     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13232     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13233     * 3) In all other cases, the install is being performed by a regular app that is neither part
13234     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13235     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13236     *    set to enterprise policy and if so, change it to unknown instead.
13237     */
13238    private int fixUpInstallReason(String installerPackageName, int installerUid,
13239            int installReason) {
13240        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13241                == PERMISSION_GRANTED) {
13242            // If the install is being performed by a system app, we trust that app to have set the
13243            // install reason correctly.
13244            return installReason;
13245        }
13246
13247        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13248            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13249        if (dpm != null) {
13250            ComponentName owner = null;
13251            try {
13252                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13253                if (owner == null) {
13254                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13255                }
13256            } catch (RemoteException e) {
13257            }
13258            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13259                // If the install is being performed by a device or profile owner, the install
13260                // reason should be enterprise policy.
13261                return PackageManager.INSTALL_REASON_POLICY;
13262            }
13263        }
13264
13265        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13266            // If the install is being performed by a regular app (i.e. neither system app nor
13267            // device or profile owner), we have no reason to believe that the app is acting on
13268            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13269            // change it to unknown instead.
13270            return PackageManager.INSTALL_REASON_UNKNOWN;
13271        }
13272
13273        // If the install is being performed by a regular app and the install reason was set to any
13274        // value but enterprise policy, leave the install reason unchanged.
13275        return installReason;
13276    }
13277
13278    void installStage(String packageName, File stagedDir,
13279            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13280            String installerPackageName, int installerUid, UserHandle user,
13281            Certificate[][] certificates) {
13282        if (DEBUG_EPHEMERAL) {
13283            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13284                Slog.d(TAG, "Ephemeral install of " + packageName);
13285            }
13286        }
13287        final VerificationInfo verificationInfo = new VerificationInfo(
13288                sessionParams.originatingUri, sessionParams.referrerUri,
13289                sessionParams.originatingUid, installerUid);
13290
13291        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
13292
13293        final Message msg = mHandler.obtainMessage(INIT_COPY);
13294        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13295                sessionParams.installReason);
13296        final InstallParams params = new InstallParams(origin, null, observer,
13297                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13298                verificationInfo, user, sessionParams.abiOverride,
13299                sessionParams.grantedRuntimePermissions, certificates, installReason);
13300        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13301        msg.obj = params;
13302
13303        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13304                System.identityHashCode(msg.obj));
13305        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13306                System.identityHashCode(msg.obj));
13307
13308        mHandler.sendMessage(msg);
13309    }
13310
13311    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13312            int userId) {
13313        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13314        final boolean isInstantApp = pkgSetting.getInstantApp(userId);
13315        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
13316        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
13317        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
13318                false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds);
13319
13320        // Send a session commit broadcast
13321        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
13322        info.installReason = pkgSetting.getInstallReason(userId);
13323        info.appPackageName = packageName;
13324        sendSessionCommitBroadcast(info, userId);
13325    }
13326
13327    @Override
13328    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
13329            boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) {
13330        if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) {
13331            return;
13332        }
13333        Bundle extras = new Bundle(1);
13334        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13335        final int uid = UserHandle.getUid(
13336                (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId);
13337        extras.putInt(Intent.EXTRA_UID, uid);
13338
13339        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13340                packageName, extras, 0, null, null, userIds, instantUserIds);
13341        if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) {
13342            mHandler.post(() -> {
13343                        for (int userId : userIds) {
13344                            sendBootCompletedBroadcastToSystemApp(
13345                                    packageName, includeStopped, userId);
13346                        }
13347                    }
13348            );
13349        }
13350    }
13351
13352    /**
13353     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13354     * automatically without needing an explicit launch.
13355     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13356     */
13357    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
13358            int userId) {
13359        // If user is not running, the app didn't miss any broadcast
13360        if (!mUserManagerInternal.isUserRunning(userId)) {
13361            return;
13362        }
13363        final IActivityManager am = ActivityManager.getService();
13364        try {
13365            // Deliver LOCKED_BOOT_COMPLETED first
13366            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13367                    .setPackage(packageName);
13368            if (includeStopped) {
13369                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13370            }
13371            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13372            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13373                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13374
13375            // Deliver BOOT_COMPLETED only if user is unlocked
13376            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13377                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13378                if (includeStopped) {
13379                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13380                }
13381                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13382                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13383            }
13384        } catch (RemoteException e) {
13385            throw e.rethrowFromSystemServer();
13386        }
13387    }
13388
13389    @Override
13390    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13391            int userId) {
13392        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13393        PackageSetting pkgSetting;
13394        final int callingUid = Binder.getCallingUid();
13395        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13396                true /* requireFullPermission */, true /* checkShell */,
13397                "setApplicationHiddenSetting for user " + userId);
13398
13399        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13400            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13401            return false;
13402        }
13403
13404        long callingId = Binder.clearCallingIdentity();
13405        try {
13406            boolean sendAdded = false;
13407            boolean sendRemoved = false;
13408            // writer
13409            synchronized (mPackages) {
13410                pkgSetting = mSettings.mPackages.get(packageName);
13411                if (pkgSetting == null) {
13412                    return false;
13413                }
13414                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13415                    return false;
13416                }
13417                // Do not allow "android" is being disabled
13418                if ("android".equals(packageName)) {
13419                    Slog.w(TAG, "Cannot hide package: android");
13420                    return false;
13421                }
13422                // Cannot hide static shared libs as they are considered
13423                // a part of the using app (emulating static linking). Also
13424                // static libs are installed always on internal storage.
13425                PackageParser.Package pkg = mPackages.get(packageName);
13426                if (pkg != null && pkg.staticSharedLibName != null) {
13427                    Slog.w(TAG, "Cannot hide package: " + packageName
13428                            + " providing static shared library: "
13429                            + pkg.staticSharedLibName);
13430                    return false;
13431                }
13432                // Only allow protected packages to hide themselves.
13433                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
13434                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13435                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13436                    return false;
13437                }
13438
13439                if (pkgSetting.getHidden(userId) != hidden) {
13440                    pkgSetting.setHidden(hidden, userId);
13441                    mSettings.writePackageRestrictionsLPr(userId);
13442                    if (hidden) {
13443                        sendRemoved = true;
13444                    } else {
13445                        sendAdded = true;
13446                    }
13447                }
13448            }
13449            if (sendAdded) {
13450                sendPackageAddedForUser(packageName, pkgSetting, userId);
13451                return true;
13452            }
13453            if (sendRemoved) {
13454                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13455                        "hiding pkg");
13456                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13457                return true;
13458            }
13459        } finally {
13460            Binder.restoreCallingIdentity(callingId);
13461        }
13462        return false;
13463    }
13464
13465    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13466            int userId) {
13467        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13468        info.removedPackage = packageName;
13469        info.installerPackageName = pkgSetting.installerPackageName;
13470        info.removedUsers = new int[] {userId};
13471        info.broadcastUsers = new int[] {userId};
13472        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13473        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13474    }
13475
13476    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13477        if (pkgList.length > 0) {
13478            Bundle extras = new Bundle(1);
13479            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13480
13481            sendPackageBroadcast(
13482                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13483                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13484                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13485                    new int[] {userId}, null);
13486        }
13487    }
13488
13489    /**
13490     * Returns true if application is not found or there was an error. Otherwise it returns
13491     * the hidden state of the package for the given user.
13492     */
13493    @Override
13494    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13495        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13496        final int callingUid = Binder.getCallingUid();
13497        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13498                true /* requireFullPermission */, false /* checkShell */,
13499                "getApplicationHidden for user " + userId);
13500        PackageSetting ps;
13501        long callingId = Binder.clearCallingIdentity();
13502        try {
13503            // writer
13504            synchronized (mPackages) {
13505                ps = mSettings.mPackages.get(packageName);
13506                if (ps == null) {
13507                    return true;
13508                }
13509                if (filterAppAccessLPr(ps, callingUid, userId)) {
13510                    return true;
13511                }
13512                return ps.getHidden(userId);
13513            }
13514        } finally {
13515            Binder.restoreCallingIdentity(callingId);
13516        }
13517    }
13518
13519    /**
13520     * @hide
13521     */
13522    @Override
13523    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13524            int installReason) {
13525        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13526                null);
13527        PackageSetting pkgSetting;
13528        final int callingUid = Binder.getCallingUid();
13529        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13530                true /* requireFullPermission */, true /* checkShell */,
13531                "installExistingPackage for user " + userId);
13532        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13533            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13534        }
13535
13536        long callingId = Binder.clearCallingIdentity();
13537        try {
13538            boolean installed = false;
13539            final boolean instantApp =
13540                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13541            final boolean fullApp =
13542                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13543
13544            // writer
13545            synchronized (mPackages) {
13546                pkgSetting = mSettings.mPackages.get(packageName);
13547                if (pkgSetting == null) {
13548                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13549                }
13550                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
13551                    // only allow the existing package to be used if it's installed as a full
13552                    // application for at least one user
13553                    boolean installAllowed = false;
13554                    for (int checkUserId : sUserManager.getUserIds()) {
13555                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
13556                        if (installAllowed) {
13557                            break;
13558                        }
13559                    }
13560                    if (!installAllowed) {
13561                        return PackageManager.INSTALL_FAILED_INVALID_URI;
13562                    }
13563                }
13564                if (!pkgSetting.getInstalled(userId)) {
13565                    pkgSetting.setInstalled(true, userId);
13566                    pkgSetting.setHidden(false, userId);
13567                    pkgSetting.setInstallReason(installReason, userId);
13568                    mSettings.writePackageRestrictionsLPr(userId);
13569                    mSettings.writeKernelMappingLPr(pkgSetting);
13570                    installed = true;
13571                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13572                    // upgrade app from instant to full; we don't allow app downgrade
13573                    installed = true;
13574                }
13575                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13576            }
13577
13578            if (installed) {
13579                if (pkgSetting.pkg != null) {
13580                    synchronized (mInstallLock) {
13581                        // We don't need to freeze for a brand new install
13582                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13583                    }
13584                }
13585                sendPackageAddedForUser(packageName, pkgSetting, userId);
13586                synchronized (mPackages) {
13587                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
13588                }
13589            }
13590        } finally {
13591            Binder.restoreCallingIdentity(callingId);
13592        }
13593
13594        return PackageManager.INSTALL_SUCCEEDED;
13595    }
13596
13597    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13598            boolean instantApp, boolean fullApp) {
13599        // no state specified; do nothing
13600        if (!instantApp && !fullApp) {
13601            return;
13602        }
13603        if (userId != UserHandle.USER_ALL) {
13604            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13605                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13606            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13607                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13608            }
13609        } else {
13610            for (int currentUserId : sUserManager.getUserIds()) {
13611                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13612                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13613                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13614                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13615                }
13616            }
13617        }
13618    }
13619
13620    boolean isUserRestricted(int userId, String restrictionKey) {
13621        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13622        if (restrictions.getBoolean(restrictionKey, false)) {
13623            Log.w(TAG, "User is restricted: " + restrictionKey);
13624            return true;
13625        }
13626        return false;
13627    }
13628
13629    @Override
13630    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13631            int userId) {
13632        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13633        final int callingUid = Binder.getCallingUid();
13634        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13635                true /* requireFullPermission */, true /* checkShell */,
13636                "setPackagesSuspended for user " + userId);
13637
13638        if (ArrayUtils.isEmpty(packageNames)) {
13639            return packageNames;
13640        }
13641
13642        // List of package names for whom the suspended state has changed.
13643        List<String> changedPackages = new ArrayList<>(packageNames.length);
13644        // List of package names for whom the suspended state is not set as requested in this
13645        // method.
13646        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13647        long callingId = Binder.clearCallingIdentity();
13648        try {
13649            for (int i = 0; i < packageNames.length; i++) {
13650                String packageName = packageNames[i];
13651                boolean changed = false;
13652                final int appId;
13653                synchronized (mPackages) {
13654                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13655                    if (pkgSetting == null
13656                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13657                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13658                                + "\". Skipping suspending/un-suspending.");
13659                        unactionedPackages.add(packageName);
13660                        continue;
13661                    }
13662                    appId = pkgSetting.appId;
13663                    if (pkgSetting.getSuspended(userId) != suspended) {
13664                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13665                            unactionedPackages.add(packageName);
13666                            continue;
13667                        }
13668                        pkgSetting.setSuspended(suspended, userId);
13669                        mSettings.writePackageRestrictionsLPr(userId);
13670                        changed = true;
13671                        changedPackages.add(packageName);
13672                    }
13673                }
13674
13675                if (changed && suspended) {
13676                    killApplication(packageName, UserHandle.getUid(userId, appId),
13677                            "suspending package");
13678                }
13679            }
13680        } finally {
13681            Binder.restoreCallingIdentity(callingId);
13682        }
13683
13684        if (!changedPackages.isEmpty()) {
13685            sendPackagesSuspendedForUser(changedPackages.toArray(
13686                    new String[changedPackages.size()]), userId, suspended);
13687        }
13688
13689        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13690    }
13691
13692    @Override
13693    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13694        final int callingUid = Binder.getCallingUid();
13695        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13696                true /* requireFullPermission */, false /* checkShell */,
13697                "isPackageSuspendedForUser for user " + userId);
13698        synchronized (mPackages) {
13699            final PackageSetting ps = mSettings.mPackages.get(packageName);
13700            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
13701                throw new IllegalArgumentException("Unknown target package: " + packageName);
13702            }
13703            return ps.getSuspended(userId);
13704        }
13705    }
13706
13707    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13708        if (isPackageDeviceAdmin(packageName, userId)) {
13709            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13710                    + "\": has an active device admin");
13711            return false;
13712        }
13713
13714        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13715        if (packageName.equals(activeLauncherPackageName)) {
13716            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13717                    + "\": contains the active launcher");
13718            return false;
13719        }
13720
13721        if (packageName.equals(mRequiredInstallerPackage)) {
13722            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13723                    + "\": required for package installation");
13724            return false;
13725        }
13726
13727        if (packageName.equals(mRequiredUninstallerPackage)) {
13728            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13729                    + "\": required for package uninstallation");
13730            return false;
13731        }
13732
13733        if (packageName.equals(mRequiredVerifierPackage)) {
13734            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13735                    + "\": required for package verification");
13736            return false;
13737        }
13738
13739        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13740            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13741                    + "\": is the default dialer");
13742            return false;
13743        }
13744
13745        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13746            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13747                    + "\": protected package");
13748            return false;
13749        }
13750
13751        // Cannot suspend static shared libs as they are considered
13752        // a part of the using app (emulating static linking). Also
13753        // static libs are installed always on internal storage.
13754        PackageParser.Package pkg = mPackages.get(packageName);
13755        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
13756            Slog.w(TAG, "Cannot suspend package: " + packageName
13757                    + " providing static shared library: "
13758                    + pkg.staticSharedLibName);
13759            return false;
13760        }
13761
13762        return true;
13763    }
13764
13765    private String getActiveLauncherPackageName(int userId) {
13766        Intent intent = new Intent(Intent.ACTION_MAIN);
13767        intent.addCategory(Intent.CATEGORY_HOME);
13768        ResolveInfo resolveInfo = resolveIntent(
13769                intent,
13770                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
13771                PackageManager.MATCH_DEFAULT_ONLY,
13772                userId);
13773
13774        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
13775    }
13776
13777    private String getDefaultDialerPackageName(int userId) {
13778        synchronized (mPackages) {
13779            return mSettings.getDefaultDialerPackageNameLPw(userId);
13780        }
13781    }
13782
13783    @Override
13784    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
13785        mContext.enforceCallingOrSelfPermission(
13786                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13787                "Only package verification agents can verify applications");
13788
13789        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13790        final PackageVerificationResponse response = new PackageVerificationResponse(
13791                verificationCode, Binder.getCallingUid());
13792        msg.arg1 = id;
13793        msg.obj = response;
13794        mHandler.sendMessage(msg);
13795    }
13796
13797    @Override
13798    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
13799            long millisecondsToDelay) {
13800        mContext.enforceCallingOrSelfPermission(
13801                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13802                "Only package verification agents can extend verification timeouts");
13803
13804        final PackageVerificationState state = mPendingVerification.get(id);
13805        final PackageVerificationResponse response = new PackageVerificationResponse(
13806                verificationCodeAtTimeout, Binder.getCallingUid());
13807
13808        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
13809            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
13810        }
13811        if (millisecondsToDelay < 0) {
13812            millisecondsToDelay = 0;
13813        }
13814        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
13815                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
13816            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
13817        }
13818
13819        if ((state != null) && !state.timeoutExtended()) {
13820            state.extendTimeout();
13821
13822            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13823            msg.arg1 = id;
13824            msg.obj = response;
13825            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
13826        }
13827    }
13828
13829    private void broadcastPackageVerified(int verificationId, Uri packageUri,
13830            int verificationCode, UserHandle user) {
13831        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
13832        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
13833        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13834        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13835        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
13836
13837        mContext.sendBroadcastAsUser(intent, user,
13838                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
13839    }
13840
13841    private ComponentName matchComponentForVerifier(String packageName,
13842            List<ResolveInfo> receivers) {
13843        ActivityInfo targetReceiver = null;
13844
13845        final int NR = receivers.size();
13846        for (int i = 0; i < NR; i++) {
13847            final ResolveInfo info = receivers.get(i);
13848            if (info.activityInfo == null) {
13849                continue;
13850            }
13851
13852            if (packageName.equals(info.activityInfo.packageName)) {
13853                targetReceiver = info.activityInfo;
13854                break;
13855            }
13856        }
13857
13858        if (targetReceiver == null) {
13859            return null;
13860        }
13861
13862        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
13863    }
13864
13865    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
13866            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
13867        if (pkgInfo.verifiers.length == 0) {
13868            return null;
13869        }
13870
13871        final int N = pkgInfo.verifiers.length;
13872        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
13873        for (int i = 0; i < N; i++) {
13874            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
13875
13876            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
13877                    receivers);
13878            if (comp == null) {
13879                continue;
13880            }
13881
13882            final int verifierUid = getUidForVerifier(verifierInfo);
13883            if (verifierUid == -1) {
13884                continue;
13885            }
13886
13887            if (DEBUG_VERIFY) {
13888                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
13889                        + " with the correct signature");
13890            }
13891            sufficientVerifiers.add(comp);
13892            verificationState.addSufficientVerifier(verifierUid);
13893        }
13894
13895        return sufficientVerifiers;
13896    }
13897
13898    private int getUidForVerifier(VerifierInfo verifierInfo) {
13899        synchronized (mPackages) {
13900            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
13901            if (pkg == null) {
13902                return -1;
13903            } else if (pkg.mSignatures.length != 1) {
13904                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13905                        + " has more than one signature; ignoring");
13906                return -1;
13907            }
13908
13909            /*
13910             * If the public key of the package's signature does not match
13911             * our expected public key, then this is a different package and
13912             * we should skip.
13913             */
13914
13915            final byte[] expectedPublicKey;
13916            try {
13917                final Signature verifierSig = pkg.mSignatures[0];
13918                final PublicKey publicKey = verifierSig.getPublicKey();
13919                expectedPublicKey = publicKey.getEncoded();
13920            } catch (CertificateException e) {
13921                return -1;
13922            }
13923
13924            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
13925
13926            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
13927                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13928                        + " does not have the expected public key; ignoring");
13929                return -1;
13930            }
13931
13932            return pkg.applicationInfo.uid;
13933        }
13934    }
13935
13936    @Override
13937    public void finishPackageInstall(int token, boolean didLaunch) {
13938        enforceSystemOrRoot("Only the system is allowed to finish installs");
13939
13940        if (DEBUG_INSTALL) {
13941            Slog.v(TAG, "BM finishing package install for " + token);
13942        }
13943        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13944
13945        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
13946        mHandler.sendMessage(msg);
13947    }
13948
13949    /**
13950     * Get the verification agent timeout.  Used for both the APK verifier and the
13951     * intent filter verifier.
13952     *
13953     * @return verification timeout in milliseconds
13954     */
13955    private long getVerificationTimeout() {
13956        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
13957                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
13958                DEFAULT_VERIFICATION_TIMEOUT);
13959    }
13960
13961    /**
13962     * Get the default verification agent response code.
13963     *
13964     * @return default verification response code
13965     */
13966    private int getDefaultVerificationResponse(UserHandle user) {
13967        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
13968            return PackageManager.VERIFICATION_REJECT;
13969        }
13970        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13971                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
13972                DEFAULT_VERIFICATION_RESPONSE);
13973    }
13974
13975    /**
13976     * Check whether or not package verification has been enabled.
13977     *
13978     * @return true if verification should be performed
13979     */
13980    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
13981        if (!DEFAULT_VERIFY_ENABLE) {
13982            return false;
13983        }
13984
13985        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
13986
13987        // Check if installing from ADB
13988        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
13989            // Do not run verification in a test harness environment
13990            if (ActivityManager.isRunningInTestHarness()) {
13991                return false;
13992            }
13993            if (ensureVerifyAppsEnabled) {
13994                return true;
13995            }
13996            // Check if the developer does not want package verification for ADB installs
13997            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13998                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
13999                return false;
14000            }
14001        } else {
14002            // only when not installed from ADB, skip verification for instant apps when
14003            // the installer and verifier are the same.
14004            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14005                if (mInstantAppInstallerActivity != null
14006                        && mInstantAppInstallerActivity.packageName.equals(
14007                                mRequiredVerifierPackage)) {
14008                    try {
14009                        mContext.getSystemService(AppOpsManager.class)
14010                                .checkPackage(installerUid, mRequiredVerifierPackage);
14011                        if (DEBUG_VERIFY) {
14012                            Slog.i(TAG, "disable verification for instant app");
14013                        }
14014                        return false;
14015                    } catch (SecurityException ignore) { }
14016                }
14017            }
14018        }
14019
14020        if (ensureVerifyAppsEnabled) {
14021            return true;
14022        }
14023
14024        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14025                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14026    }
14027
14028    @Override
14029    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14030            throws RemoteException {
14031        mContext.enforceCallingOrSelfPermission(
14032                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14033                "Only intentfilter verification agents can verify applications");
14034
14035        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14036        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14037                Binder.getCallingUid(), verificationCode, failedDomains);
14038        msg.arg1 = id;
14039        msg.obj = response;
14040        mHandler.sendMessage(msg);
14041    }
14042
14043    @Override
14044    public int getIntentVerificationStatus(String packageName, int userId) {
14045        final int callingUid = Binder.getCallingUid();
14046        if (UserHandle.getUserId(callingUid) != userId) {
14047            mContext.enforceCallingOrSelfPermission(
14048                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14049                    "getIntentVerificationStatus" + userId);
14050        }
14051        if (getInstantAppPackageName(callingUid) != null) {
14052            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14053        }
14054        synchronized (mPackages) {
14055            final PackageSetting ps = mSettings.mPackages.get(packageName);
14056            if (ps == null
14057                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14058                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14059            }
14060            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14061        }
14062    }
14063
14064    @Override
14065    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14066        mContext.enforceCallingOrSelfPermission(
14067                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14068
14069        boolean result = false;
14070        synchronized (mPackages) {
14071            final PackageSetting ps = mSettings.mPackages.get(packageName);
14072            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14073                return false;
14074            }
14075            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14076        }
14077        if (result) {
14078            scheduleWritePackageRestrictionsLocked(userId);
14079        }
14080        return result;
14081    }
14082
14083    @Override
14084    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14085            String packageName) {
14086        final int callingUid = Binder.getCallingUid();
14087        if (getInstantAppPackageName(callingUid) != null) {
14088            return ParceledListSlice.emptyList();
14089        }
14090        synchronized (mPackages) {
14091            final PackageSetting ps = mSettings.mPackages.get(packageName);
14092            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14093                return ParceledListSlice.emptyList();
14094            }
14095            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14096        }
14097    }
14098
14099    @Override
14100    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14101        if (TextUtils.isEmpty(packageName)) {
14102            return ParceledListSlice.emptyList();
14103        }
14104        final int callingUid = Binder.getCallingUid();
14105        final int callingUserId = UserHandle.getUserId(callingUid);
14106        synchronized (mPackages) {
14107            PackageParser.Package pkg = mPackages.get(packageName);
14108            if (pkg == null || pkg.activities == null) {
14109                return ParceledListSlice.emptyList();
14110            }
14111            if (pkg.mExtras == null) {
14112                return ParceledListSlice.emptyList();
14113            }
14114            final PackageSetting ps = (PackageSetting) pkg.mExtras;
14115            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14116                return ParceledListSlice.emptyList();
14117            }
14118            final int count = pkg.activities.size();
14119            ArrayList<IntentFilter> result = new ArrayList<>();
14120            for (int n=0; n<count; n++) {
14121                PackageParser.Activity activity = pkg.activities.get(n);
14122                if (activity.intents != null && activity.intents.size() > 0) {
14123                    result.addAll(activity.intents);
14124                }
14125            }
14126            return new ParceledListSlice<>(result);
14127        }
14128    }
14129
14130    @Override
14131    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14132        mContext.enforceCallingOrSelfPermission(
14133                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14134        if (UserHandle.getCallingUserId() != userId) {
14135            mContext.enforceCallingOrSelfPermission(
14136                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14137        }
14138
14139        synchronized (mPackages) {
14140            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14141            if (packageName != null) {
14142                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
14143                        packageName, userId);
14144            }
14145            return result;
14146        }
14147    }
14148
14149    @Override
14150    public String getDefaultBrowserPackageName(int userId) {
14151        if (UserHandle.getCallingUserId() != userId) {
14152            mContext.enforceCallingOrSelfPermission(
14153                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14154        }
14155        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14156            return null;
14157        }
14158        synchronized (mPackages) {
14159            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14160        }
14161    }
14162
14163    /**
14164     * Get the "allow unknown sources" setting.
14165     *
14166     * @return the current "allow unknown sources" setting
14167     */
14168    private int getUnknownSourcesSettings() {
14169        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14170                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14171                -1);
14172    }
14173
14174    @Override
14175    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14176        final int callingUid = Binder.getCallingUid();
14177        if (getInstantAppPackageName(callingUid) != null) {
14178            return;
14179        }
14180        // writer
14181        synchronized (mPackages) {
14182            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14183            if (targetPackageSetting == null
14184                    || filterAppAccessLPr(
14185                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
14186                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14187            }
14188
14189            PackageSetting installerPackageSetting;
14190            if (installerPackageName != null) {
14191                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14192                if (installerPackageSetting == null) {
14193                    throw new IllegalArgumentException("Unknown installer package: "
14194                            + installerPackageName);
14195                }
14196            } else {
14197                installerPackageSetting = null;
14198            }
14199
14200            Signature[] callerSignature;
14201            Object obj = mSettings.getUserIdLPr(callingUid);
14202            if (obj != null) {
14203                if (obj instanceof SharedUserSetting) {
14204                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
14205                } else if (obj instanceof PackageSetting) {
14206                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
14207                } else {
14208                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
14209                }
14210            } else {
14211                throw new SecurityException("Unknown calling UID: " + callingUid);
14212            }
14213
14214            // Verify: can't set installerPackageName to a package that is
14215            // not signed with the same cert as the caller.
14216            if (installerPackageSetting != null) {
14217                if (compareSignatures(callerSignature,
14218                        installerPackageSetting.signatures.mSignatures)
14219                        != PackageManager.SIGNATURE_MATCH) {
14220                    throw new SecurityException(
14221                            "Caller does not have same cert as new installer package "
14222                            + installerPackageName);
14223                }
14224            }
14225
14226            // Verify: if target already has an installer package, it must
14227            // be signed with the same cert as the caller.
14228            if (targetPackageSetting.installerPackageName != null) {
14229                PackageSetting setting = mSettings.mPackages.get(
14230                        targetPackageSetting.installerPackageName);
14231                // If the currently set package isn't valid, then it's always
14232                // okay to change it.
14233                if (setting != null) {
14234                    if (compareSignatures(callerSignature,
14235                            setting.signatures.mSignatures)
14236                            != PackageManager.SIGNATURE_MATCH) {
14237                        throw new SecurityException(
14238                                "Caller does not have same cert as old installer package "
14239                                + targetPackageSetting.installerPackageName);
14240                    }
14241                }
14242            }
14243
14244            // Okay!
14245            targetPackageSetting.installerPackageName = installerPackageName;
14246            if (installerPackageName != null) {
14247                mSettings.mInstallerPackages.add(installerPackageName);
14248            }
14249            scheduleWriteSettingsLocked();
14250        }
14251    }
14252
14253    @Override
14254    public void setApplicationCategoryHint(String packageName, int categoryHint,
14255            String callerPackageName) {
14256        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14257            throw new SecurityException("Instant applications don't have access to this method");
14258        }
14259        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14260                callerPackageName);
14261        synchronized (mPackages) {
14262            PackageSetting ps = mSettings.mPackages.get(packageName);
14263            if (ps == null) {
14264                throw new IllegalArgumentException("Unknown target package " + packageName);
14265            }
14266            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14267                throw new IllegalArgumentException("Unknown target package " + packageName);
14268            }
14269            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14270                throw new IllegalArgumentException("Calling package " + callerPackageName
14271                        + " is not installer for " + packageName);
14272            }
14273
14274            if (ps.categoryHint != categoryHint) {
14275                ps.categoryHint = categoryHint;
14276                scheduleWriteSettingsLocked();
14277            }
14278        }
14279    }
14280
14281    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14282        // Queue up an async operation since the package installation may take a little while.
14283        mHandler.post(new Runnable() {
14284            public void run() {
14285                mHandler.removeCallbacks(this);
14286                 // Result object to be returned
14287                PackageInstalledInfo res = new PackageInstalledInfo();
14288                res.setReturnCode(currentStatus);
14289                res.uid = -1;
14290                res.pkg = null;
14291                res.removedInfo = null;
14292                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14293                    args.doPreInstall(res.returnCode);
14294                    synchronized (mInstallLock) {
14295                        installPackageTracedLI(args, res);
14296                    }
14297                    args.doPostInstall(res.returnCode, res.uid);
14298                }
14299
14300                // A restore should be performed at this point if (a) the install
14301                // succeeded, (b) the operation is not an update, and (c) the new
14302                // package has not opted out of backup participation.
14303                final boolean update = res.removedInfo != null
14304                        && res.removedInfo.removedPackage != null;
14305                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14306                boolean doRestore = !update
14307                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14308
14309                // Set up the post-install work request bookkeeping.  This will be used
14310                // and cleaned up by the post-install event handling regardless of whether
14311                // there's a restore pass performed.  Token values are >= 1.
14312                int token;
14313                if (mNextInstallToken < 0) mNextInstallToken = 1;
14314                token = mNextInstallToken++;
14315
14316                PostInstallData data = new PostInstallData(args, res);
14317                mRunningInstalls.put(token, data);
14318                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14319
14320                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14321                    // Pass responsibility to the Backup Manager.  It will perform a
14322                    // restore if appropriate, then pass responsibility back to the
14323                    // Package Manager to run the post-install observer callbacks
14324                    // and broadcasts.
14325                    IBackupManager bm = IBackupManager.Stub.asInterface(
14326                            ServiceManager.getService(Context.BACKUP_SERVICE));
14327                    if (bm != null) {
14328                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14329                                + " to BM for possible restore");
14330                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14331                        try {
14332                            // TODO: http://b/22388012
14333                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14334                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14335                            } else {
14336                                doRestore = false;
14337                            }
14338                        } catch (RemoteException e) {
14339                            // can't happen; the backup manager is local
14340                        } catch (Exception e) {
14341                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14342                            doRestore = false;
14343                        }
14344                    } else {
14345                        Slog.e(TAG, "Backup Manager not found!");
14346                        doRestore = false;
14347                    }
14348                }
14349
14350                if (!doRestore) {
14351                    // No restore possible, or the Backup Manager was mysteriously not
14352                    // available -- just fire the post-install work request directly.
14353                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14354
14355                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14356
14357                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14358                    mHandler.sendMessage(msg);
14359                }
14360            }
14361        });
14362    }
14363
14364    /**
14365     * Callback from PackageSettings whenever an app is first transitioned out of the
14366     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14367     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14368     * here whether the app is the target of an ongoing install, and only send the
14369     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14370     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14371     * handling.
14372     */
14373    void notifyFirstLaunch(final String packageName, final String installerPackage,
14374            final int userId) {
14375        // Serialize this with the rest of the install-process message chain.  In the
14376        // restore-at-install case, this Runnable will necessarily run before the
14377        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14378        // are coherent.  In the non-restore case, the app has already completed install
14379        // and been launched through some other means, so it is not in a problematic
14380        // state for observers to see the FIRST_LAUNCH signal.
14381        mHandler.post(new Runnable() {
14382            @Override
14383            public void run() {
14384                for (int i = 0; i < mRunningInstalls.size(); i++) {
14385                    final PostInstallData data = mRunningInstalls.valueAt(i);
14386                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14387                        continue;
14388                    }
14389                    if (packageName.equals(data.res.pkg.applicationInfo.packageName)) {
14390                        // right package; but is it for the right user?
14391                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14392                            if (userId == data.res.newUsers[uIndex]) {
14393                                if (DEBUG_BACKUP) {
14394                                    Slog.i(TAG, "Package " + packageName
14395                                            + " being restored so deferring FIRST_LAUNCH");
14396                                }
14397                                return;
14398                            }
14399                        }
14400                    }
14401                }
14402                // didn't find it, so not being restored
14403                if (DEBUG_BACKUP) {
14404                    Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH");
14405                }
14406                final boolean isInstantApp = isInstantApp(packageName, userId);
14407                final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
14408                final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
14409                sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds);
14410            }
14411        });
14412    }
14413
14414    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg,
14415            int[] userIds, int[] instantUserIds) {
14416        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14417                installerPkg, null, userIds, instantUserIds);
14418    }
14419
14420    private abstract class HandlerParams {
14421        private static final int MAX_RETRIES = 4;
14422
14423        /**
14424         * Number of times startCopy() has been attempted and had a non-fatal
14425         * error.
14426         */
14427        private int mRetries = 0;
14428
14429        /** User handle for the user requesting the information or installation. */
14430        private final UserHandle mUser;
14431        String traceMethod;
14432        int traceCookie;
14433
14434        HandlerParams(UserHandle user) {
14435            mUser = user;
14436        }
14437
14438        UserHandle getUser() {
14439            return mUser;
14440        }
14441
14442        HandlerParams setTraceMethod(String traceMethod) {
14443            this.traceMethod = traceMethod;
14444            return this;
14445        }
14446
14447        HandlerParams setTraceCookie(int traceCookie) {
14448            this.traceCookie = traceCookie;
14449            return this;
14450        }
14451
14452        final boolean startCopy() {
14453            boolean res;
14454            try {
14455                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14456
14457                if (++mRetries > MAX_RETRIES) {
14458                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14459                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14460                    handleServiceError();
14461                    return false;
14462                } else {
14463                    handleStartCopy();
14464                    res = true;
14465                }
14466            } catch (RemoteException e) {
14467                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14468                mHandler.sendEmptyMessage(MCS_RECONNECT);
14469                res = false;
14470            }
14471            handleReturnCode();
14472            return res;
14473        }
14474
14475        final void serviceError() {
14476            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14477            handleServiceError();
14478            handleReturnCode();
14479        }
14480
14481        abstract void handleStartCopy() throws RemoteException;
14482        abstract void handleServiceError();
14483        abstract void handleReturnCode();
14484    }
14485
14486    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14487        for (File path : paths) {
14488            try {
14489                mcs.clearDirectory(path.getAbsolutePath());
14490            } catch (RemoteException e) {
14491            }
14492        }
14493    }
14494
14495    static class OriginInfo {
14496        /**
14497         * Location where install is coming from, before it has been
14498         * copied/renamed into place. This could be a single monolithic APK
14499         * file, or a cluster directory. This location may be untrusted.
14500         */
14501        final File file;
14502
14503        /**
14504         * Flag indicating that {@link #file} or {@link #cid} has already been
14505         * staged, meaning downstream users don't need to defensively copy the
14506         * contents.
14507         */
14508        final boolean staged;
14509
14510        /**
14511         * Flag indicating that {@link #file} or {@link #cid} is an already
14512         * installed app that is being moved.
14513         */
14514        final boolean existing;
14515
14516        final String resolvedPath;
14517        final File resolvedFile;
14518
14519        static OriginInfo fromNothing() {
14520            return new OriginInfo(null, false, false);
14521        }
14522
14523        static OriginInfo fromUntrustedFile(File file) {
14524            return new OriginInfo(file, false, false);
14525        }
14526
14527        static OriginInfo fromExistingFile(File file) {
14528            return new OriginInfo(file, false, true);
14529        }
14530
14531        static OriginInfo fromStagedFile(File file) {
14532            return new OriginInfo(file, true, false);
14533        }
14534
14535        private OriginInfo(File file, boolean staged, boolean existing) {
14536            this.file = file;
14537            this.staged = staged;
14538            this.existing = existing;
14539
14540            if (file != null) {
14541                resolvedPath = file.getAbsolutePath();
14542                resolvedFile = file;
14543            } else {
14544                resolvedPath = null;
14545                resolvedFile = null;
14546            }
14547        }
14548    }
14549
14550    static class MoveInfo {
14551        final int moveId;
14552        final String fromUuid;
14553        final String toUuid;
14554        final String packageName;
14555        final String dataAppName;
14556        final int appId;
14557        final String seinfo;
14558        final int targetSdkVersion;
14559
14560        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14561                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14562            this.moveId = moveId;
14563            this.fromUuid = fromUuid;
14564            this.toUuid = toUuid;
14565            this.packageName = packageName;
14566            this.dataAppName = dataAppName;
14567            this.appId = appId;
14568            this.seinfo = seinfo;
14569            this.targetSdkVersion = targetSdkVersion;
14570        }
14571    }
14572
14573    static class VerificationInfo {
14574        /** A constant used to indicate that a uid value is not present. */
14575        public static final int NO_UID = -1;
14576
14577        /** URI referencing where the package was downloaded from. */
14578        final Uri originatingUri;
14579
14580        /** HTTP referrer URI associated with the originatingURI. */
14581        final Uri referrer;
14582
14583        /** UID of the application that the install request originated from. */
14584        final int originatingUid;
14585
14586        /** UID of application requesting the install */
14587        final int installerUid;
14588
14589        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14590            this.originatingUri = originatingUri;
14591            this.referrer = referrer;
14592            this.originatingUid = originatingUid;
14593            this.installerUid = installerUid;
14594        }
14595    }
14596
14597    class InstallParams extends HandlerParams {
14598        final OriginInfo origin;
14599        final MoveInfo move;
14600        final IPackageInstallObserver2 observer;
14601        int installFlags;
14602        final String installerPackageName;
14603        final String volumeUuid;
14604        private InstallArgs mArgs;
14605        private int mRet;
14606        final String packageAbiOverride;
14607        final String[] grantedRuntimePermissions;
14608        final VerificationInfo verificationInfo;
14609        final Certificate[][] certificates;
14610        final int installReason;
14611
14612        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14613                int installFlags, String installerPackageName, String volumeUuid,
14614                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14615                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
14616            super(user);
14617            this.origin = origin;
14618            this.move = move;
14619            this.observer = observer;
14620            this.installFlags = installFlags;
14621            this.installerPackageName = installerPackageName;
14622            this.volumeUuid = volumeUuid;
14623            this.verificationInfo = verificationInfo;
14624            this.packageAbiOverride = packageAbiOverride;
14625            this.grantedRuntimePermissions = grantedPermissions;
14626            this.certificates = certificates;
14627            this.installReason = installReason;
14628        }
14629
14630        @Override
14631        public String toString() {
14632            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14633                    + " file=" + origin.file + "}";
14634        }
14635
14636        private int installLocationPolicy(PackageInfoLite pkgLite) {
14637            String packageName = pkgLite.packageName;
14638            int installLocation = pkgLite.installLocation;
14639            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14640            // reader
14641            synchronized (mPackages) {
14642                // Currently installed package which the new package is attempting to replace or
14643                // null if no such package is installed.
14644                PackageParser.Package installedPkg = mPackages.get(packageName);
14645                // Package which currently owns the data which the new package will own if installed.
14646                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14647                // will be null whereas dataOwnerPkg will contain information about the package
14648                // which was uninstalled while keeping its data.
14649                PackageParser.Package dataOwnerPkg = installedPkg;
14650                if (dataOwnerPkg  == null) {
14651                    PackageSetting ps = mSettings.mPackages.get(packageName);
14652                    if (ps != null) {
14653                        dataOwnerPkg = ps.pkg;
14654                    }
14655                }
14656
14657                if (dataOwnerPkg != null) {
14658                    // If installed, the package will get access to data left on the device by its
14659                    // predecessor. As a security measure, this is permited only if this is not a
14660                    // version downgrade or if the predecessor package is marked as debuggable and
14661                    // a downgrade is explicitly requested.
14662                    //
14663                    // On debuggable platform builds, downgrades are permitted even for
14664                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14665                    // not offer security guarantees and thus it's OK to disable some security
14666                    // mechanisms to make debugging/testing easier on those builds. However, even on
14667                    // debuggable builds downgrades of packages are permitted only if requested via
14668                    // installFlags. This is because we aim to keep the behavior of debuggable
14669                    // platform builds as close as possible to the behavior of non-debuggable
14670                    // platform builds.
14671                    final boolean downgradeRequested =
14672                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14673                    final boolean packageDebuggable =
14674                                (dataOwnerPkg.applicationInfo.flags
14675                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14676                    final boolean downgradePermitted =
14677                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14678                    if (!downgradePermitted) {
14679                        try {
14680                            checkDowngrade(dataOwnerPkg, pkgLite);
14681                        } catch (PackageManagerException e) {
14682                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14683                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14684                        }
14685                    }
14686                }
14687
14688                if (installedPkg != null) {
14689                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14690                        // Check for updated system application.
14691                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14692                            if (onSd) {
14693                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14694                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14695                            }
14696                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14697                        } else {
14698                            if (onSd) {
14699                                // Install flag overrides everything.
14700                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14701                            }
14702                            // If current upgrade specifies particular preference
14703                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14704                                // Application explicitly specified internal.
14705                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14706                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14707                                // App explictly prefers external. Let policy decide
14708                            } else {
14709                                // Prefer previous location
14710                                if (isExternal(installedPkg)) {
14711                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14712                                }
14713                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14714                            }
14715                        }
14716                    } else {
14717                        // Invalid install. Return error code
14718                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14719                    }
14720                }
14721            }
14722            // All the special cases have been taken care of.
14723            // Return result based on recommended install location.
14724            if (onSd) {
14725                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14726            }
14727            return pkgLite.recommendedInstallLocation;
14728        }
14729
14730        /*
14731         * Invoke remote method to get package information and install
14732         * location values. Override install location based on default
14733         * policy if needed and then create install arguments based
14734         * on the install location.
14735         */
14736        public void handleStartCopy() throws RemoteException {
14737            int ret = PackageManager.INSTALL_SUCCEEDED;
14738
14739            // If we're already staged, we've firmly committed to an install location
14740            if (origin.staged) {
14741                if (origin.file != null) {
14742                    installFlags |= PackageManager.INSTALL_INTERNAL;
14743                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14744                } else {
14745                    throw new IllegalStateException("Invalid stage location");
14746                }
14747            }
14748
14749            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14750            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14751            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14752            PackageInfoLite pkgLite = null;
14753
14754            if (onInt && onSd) {
14755                // Check if both bits are set.
14756                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14757                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14758            } else if (onSd && ephemeral) {
14759                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14760                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14761            } else {
14762                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14763                        packageAbiOverride);
14764
14765                if (DEBUG_EPHEMERAL && ephemeral) {
14766                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14767                }
14768
14769                /*
14770                 * If we have too little free space, try to free cache
14771                 * before giving up.
14772                 */
14773                if (!origin.staged && pkgLite.recommendedInstallLocation
14774                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14775                    // TODO: focus freeing disk space on the target device
14776                    final StorageManager storage = StorageManager.from(mContext);
14777                    final long lowThreshold = storage.getStorageLowBytes(
14778                            Environment.getDataDirectory());
14779
14780                    final long sizeBytes = mContainerService.calculateInstalledSize(
14781                            origin.resolvedPath, packageAbiOverride);
14782
14783                    try {
14784                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
14785                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
14786                                installFlags, packageAbiOverride);
14787                    } catch (InstallerException e) {
14788                        Slog.w(TAG, "Failed to free cache", e);
14789                    }
14790
14791                    /*
14792                     * The cache free must have deleted the file we
14793                     * downloaded to install.
14794                     *
14795                     * TODO: fix the "freeCache" call to not delete
14796                     *       the file we care about.
14797                     */
14798                    if (pkgLite.recommendedInstallLocation
14799                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14800                        pkgLite.recommendedInstallLocation
14801                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
14802                    }
14803                }
14804            }
14805
14806            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14807                int loc = pkgLite.recommendedInstallLocation;
14808                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
14809                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14810                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
14811                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
14812                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14813                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14814                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
14815                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
14816                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14817                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
14818                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
14819                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
14820                } else {
14821                    // Override with defaults if needed.
14822                    loc = installLocationPolicy(pkgLite);
14823                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
14824                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
14825                    } else if (!onSd && !onInt) {
14826                        // Override install location with flags
14827                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
14828                            // Set the flag to install on external media.
14829                            installFlags |= PackageManager.INSTALL_EXTERNAL;
14830                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
14831                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
14832                            if (DEBUG_EPHEMERAL) {
14833                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
14834                            }
14835                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
14836                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
14837                                    |PackageManager.INSTALL_INTERNAL);
14838                        } else {
14839                            // Make sure the flag for installing on external
14840                            // media is unset
14841                            installFlags |= PackageManager.INSTALL_INTERNAL;
14842                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14843                        }
14844                    }
14845                }
14846            }
14847
14848            final InstallArgs args = createInstallArgs(this);
14849            mArgs = args;
14850
14851            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14852                // TODO: http://b/22976637
14853                // Apps installed for "all" users use the device owner to verify the app
14854                UserHandle verifierUser = getUser();
14855                if (verifierUser == UserHandle.ALL) {
14856                    verifierUser = UserHandle.SYSTEM;
14857                }
14858
14859                /*
14860                 * Determine if we have any installed package verifiers. If we
14861                 * do, then we'll defer to them to verify the packages.
14862                 */
14863                final int requiredUid = mRequiredVerifierPackage == null ? -1
14864                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
14865                                verifierUser.getIdentifier());
14866                final int installerUid =
14867                        verificationInfo == null ? -1 : verificationInfo.installerUid;
14868                if (!origin.existing && requiredUid != -1
14869                        && isVerificationEnabled(
14870                                verifierUser.getIdentifier(), installFlags, installerUid)) {
14871                    final Intent verification = new Intent(
14872                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
14873                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
14874                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
14875                            PACKAGE_MIME_TYPE);
14876                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14877
14878                    // Query all live verifiers based on current user state
14879                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
14880                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
14881                            false /*allowDynamicSplits*/);
14882
14883                    if (DEBUG_VERIFY) {
14884                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
14885                                + verification.toString() + " with " + pkgLite.verifiers.length
14886                                + " optional verifiers");
14887                    }
14888
14889                    final int verificationId = mPendingVerificationToken++;
14890
14891                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14892
14893                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
14894                            installerPackageName);
14895
14896                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
14897                            installFlags);
14898
14899                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
14900                            pkgLite.packageName);
14901
14902                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
14903                            pkgLite.versionCode);
14904
14905                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE,
14906                            pkgLite.getLongVersionCode());
14907
14908                    if (verificationInfo != null) {
14909                        if (verificationInfo.originatingUri != null) {
14910                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
14911                                    verificationInfo.originatingUri);
14912                        }
14913                        if (verificationInfo.referrer != null) {
14914                            verification.putExtra(Intent.EXTRA_REFERRER,
14915                                    verificationInfo.referrer);
14916                        }
14917                        if (verificationInfo.originatingUid >= 0) {
14918                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
14919                                    verificationInfo.originatingUid);
14920                        }
14921                        if (verificationInfo.installerUid >= 0) {
14922                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
14923                                    verificationInfo.installerUid);
14924                        }
14925                    }
14926
14927                    final PackageVerificationState verificationState = new PackageVerificationState(
14928                            requiredUid, args);
14929
14930                    mPendingVerification.append(verificationId, verificationState);
14931
14932                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
14933                            receivers, verificationState);
14934
14935                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
14936                    final long idleDuration = getVerificationTimeout();
14937
14938                    /*
14939                     * If any sufficient verifiers were listed in the package
14940                     * manifest, attempt to ask them.
14941                     */
14942                    if (sufficientVerifiers != null) {
14943                        final int N = sufficientVerifiers.size();
14944                        if (N == 0) {
14945                            Slog.i(TAG, "Additional verifiers required, but none installed.");
14946                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
14947                        } else {
14948                            for (int i = 0; i < N; i++) {
14949                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
14950                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14951                                        verifierComponent.getPackageName(), idleDuration,
14952                                        verifierUser.getIdentifier(), false, "package verifier");
14953
14954                                final Intent sufficientIntent = new Intent(verification);
14955                                sufficientIntent.setComponent(verifierComponent);
14956                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
14957                            }
14958                        }
14959                    }
14960
14961                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
14962                            mRequiredVerifierPackage, receivers);
14963                    if (ret == PackageManager.INSTALL_SUCCEEDED
14964                            && mRequiredVerifierPackage != null) {
14965                        Trace.asyncTraceBegin(
14966                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
14967                        /*
14968                         * Send the intent to the required verification agent,
14969                         * but only start the verification timeout after the
14970                         * target BroadcastReceivers have run.
14971                         */
14972                        verification.setComponent(requiredVerifierComponent);
14973                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14974                                mRequiredVerifierPackage, idleDuration,
14975                                verifierUser.getIdentifier(), false, "package verifier");
14976                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
14977                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14978                                new BroadcastReceiver() {
14979                                    @Override
14980                                    public void onReceive(Context context, Intent intent) {
14981                                        final Message msg = mHandler
14982                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
14983                                        msg.arg1 = verificationId;
14984                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
14985                                    }
14986                                }, null, 0, null, null);
14987
14988                        /*
14989                         * We don't want the copy to proceed until verification
14990                         * succeeds, so null out this field.
14991                         */
14992                        mArgs = null;
14993                    }
14994                } else {
14995                    /*
14996                     * No package verification is enabled, so immediately start
14997                     * the remote call to initiate copy using temporary file.
14998                     */
14999                    ret = args.copyApk(mContainerService, true);
15000                }
15001            }
15002
15003            mRet = ret;
15004        }
15005
15006        @Override
15007        void handleReturnCode() {
15008            // If mArgs is null, then MCS couldn't be reached. When it
15009            // reconnects, it will try again to install. At that point, this
15010            // will succeed.
15011            if (mArgs != null) {
15012                processPendingInstall(mArgs, mRet);
15013            }
15014        }
15015
15016        @Override
15017        void handleServiceError() {
15018            mArgs = createInstallArgs(this);
15019            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15020        }
15021    }
15022
15023    private InstallArgs createInstallArgs(InstallParams params) {
15024        if (params.move != null) {
15025            return new MoveInstallArgs(params);
15026        } else {
15027            return new FileInstallArgs(params);
15028        }
15029    }
15030
15031    /**
15032     * Create args that describe an existing installed package. Typically used
15033     * when cleaning up old installs, or used as a move source.
15034     */
15035    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15036            String resourcePath, String[] instructionSets) {
15037        return new FileInstallArgs(codePath, resourcePath, instructionSets);
15038    }
15039
15040    static abstract class InstallArgs {
15041        /** @see InstallParams#origin */
15042        final OriginInfo origin;
15043        /** @see InstallParams#move */
15044        final MoveInfo move;
15045
15046        final IPackageInstallObserver2 observer;
15047        // Always refers to PackageManager flags only
15048        final int installFlags;
15049        final String installerPackageName;
15050        final String volumeUuid;
15051        final UserHandle user;
15052        final String abiOverride;
15053        final String[] installGrantPermissions;
15054        /** If non-null, drop an async trace when the install completes */
15055        final String traceMethod;
15056        final int traceCookie;
15057        final Certificate[][] certificates;
15058        final int installReason;
15059
15060        // The list of instruction sets supported by this app. This is currently
15061        // only used during the rmdex() phase to clean up resources. We can get rid of this
15062        // if we move dex files under the common app path.
15063        /* nullable */ String[] instructionSets;
15064
15065        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15066                int installFlags, String installerPackageName, String volumeUuid,
15067                UserHandle user, String[] instructionSets,
15068                String abiOverride, String[] installGrantPermissions,
15069                String traceMethod, int traceCookie, Certificate[][] certificates,
15070                int installReason) {
15071            this.origin = origin;
15072            this.move = move;
15073            this.installFlags = installFlags;
15074            this.observer = observer;
15075            this.installerPackageName = installerPackageName;
15076            this.volumeUuid = volumeUuid;
15077            this.user = user;
15078            this.instructionSets = instructionSets;
15079            this.abiOverride = abiOverride;
15080            this.installGrantPermissions = installGrantPermissions;
15081            this.traceMethod = traceMethod;
15082            this.traceCookie = traceCookie;
15083            this.certificates = certificates;
15084            this.installReason = installReason;
15085        }
15086
15087        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15088        abstract int doPreInstall(int status);
15089
15090        /**
15091         * Rename package into final resting place. All paths on the given
15092         * scanned package should be updated to reflect the rename.
15093         */
15094        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15095        abstract int doPostInstall(int status, int uid);
15096
15097        /** @see PackageSettingBase#codePathString */
15098        abstract String getCodePath();
15099        /** @see PackageSettingBase#resourcePathString */
15100        abstract String getResourcePath();
15101
15102        // Need installer lock especially for dex file removal.
15103        abstract void cleanUpResourcesLI();
15104        abstract boolean doPostDeleteLI(boolean delete);
15105
15106        /**
15107         * Called before the source arguments are copied. This is used mostly
15108         * for MoveParams when it needs to read the source file to put it in the
15109         * destination.
15110         */
15111        int doPreCopy() {
15112            return PackageManager.INSTALL_SUCCEEDED;
15113        }
15114
15115        /**
15116         * Called after the source arguments are copied. This is used mostly for
15117         * MoveParams when it needs to read the source file to put it in the
15118         * destination.
15119         */
15120        int doPostCopy(int uid) {
15121            return PackageManager.INSTALL_SUCCEEDED;
15122        }
15123
15124        protected boolean isFwdLocked() {
15125            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15126        }
15127
15128        protected boolean isExternalAsec() {
15129            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15130        }
15131
15132        protected boolean isEphemeral() {
15133            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15134        }
15135
15136        UserHandle getUser() {
15137            return user;
15138        }
15139    }
15140
15141    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15142        if (!allCodePaths.isEmpty()) {
15143            if (instructionSets == null) {
15144                throw new IllegalStateException("instructionSet == null");
15145            }
15146            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15147            for (String codePath : allCodePaths) {
15148                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15149                    try {
15150                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15151                    } catch (InstallerException ignored) {
15152                    }
15153                }
15154            }
15155        }
15156    }
15157
15158    /**
15159     * Logic to handle installation of non-ASEC applications, including copying
15160     * and renaming logic.
15161     */
15162    class FileInstallArgs extends InstallArgs {
15163        private File codeFile;
15164        private File resourceFile;
15165
15166        // Example topology:
15167        // /data/app/com.example/base.apk
15168        // /data/app/com.example/split_foo.apk
15169        // /data/app/com.example/lib/arm/libfoo.so
15170        // /data/app/com.example/lib/arm64/libfoo.so
15171        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15172
15173        /** New install */
15174        FileInstallArgs(InstallParams params) {
15175            super(params.origin, params.move, params.observer, params.installFlags,
15176                    params.installerPackageName, params.volumeUuid,
15177                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15178                    params.grantedRuntimePermissions,
15179                    params.traceMethod, params.traceCookie, params.certificates,
15180                    params.installReason);
15181            if (isFwdLocked()) {
15182                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15183            }
15184        }
15185
15186        /** Existing install */
15187        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15188            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15189                    null, null, null, 0, null /*certificates*/,
15190                    PackageManager.INSTALL_REASON_UNKNOWN);
15191            this.codeFile = (codePath != null) ? new File(codePath) : null;
15192            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15193        }
15194
15195        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15196            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15197            try {
15198                return doCopyApk(imcs, temp);
15199            } finally {
15200                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15201            }
15202        }
15203
15204        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15205            if (origin.staged) {
15206                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15207                codeFile = origin.file;
15208                resourceFile = origin.file;
15209                return PackageManager.INSTALL_SUCCEEDED;
15210            }
15211
15212            try {
15213                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15214                final File tempDir =
15215                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15216                codeFile = tempDir;
15217                resourceFile = tempDir;
15218            } catch (IOException e) {
15219                Slog.w(TAG, "Failed to create copy file: " + e);
15220                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15221            }
15222
15223            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15224                @Override
15225                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15226                    if (!FileUtils.isValidExtFilename(name)) {
15227                        throw new IllegalArgumentException("Invalid filename: " + name);
15228                    }
15229                    try {
15230                        final File file = new File(codeFile, name);
15231                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15232                                O_RDWR | O_CREAT, 0644);
15233                        Os.chmod(file.getAbsolutePath(), 0644);
15234                        return new ParcelFileDescriptor(fd);
15235                    } catch (ErrnoException e) {
15236                        throw new RemoteException("Failed to open: " + e.getMessage());
15237                    }
15238                }
15239            };
15240
15241            int ret = PackageManager.INSTALL_SUCCEEDED;
15242            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15243            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15244                Slog.e(TAG, "Failed to copy package");
15245                return ret;
15246            }
15247
15248            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15249            NativeLibraryHelper.Handle handle = null;
15250            try {
15251                handle = NativeLibraryHelper.Handle.create(codeFile);
15252                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15253                        abiOverride);
15254            } catch (IOException e) {
15255                Slog.e(TAG, "Copying native libraries failed", e);
15256                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15257            } finally {
15258                IoUtils.closeQuietly(handle);
15259            }
15260
15261            return ret;
15262        }
15263
15264        int doPreInstall(int status) {
15265            if (status != PackageManager.INSTALL_SUCCEEDED) {
15266                cleanUp();
15267            }
15268            return status;
15269        }
15270
15271        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15272            if (status != PackageManager.INSTALL_SUCCEEDED) {
15273                cleanUp();
15274                return false;
15275            }
15276
15277            final File targetDir = codeFile.getParentFile();
15278            final File beforeCodeFile = codeFile;
15279            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15280
15281            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15282            try {
15283                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15284            } catch (ErrnoException e) {
15285                Slog.w(TAG, "Failed to rename", e);
15286                return false;
15287            }
15288
15289            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15290                Slog.w(TAG, "Failed to restorecon");
15291                return false;
15292            }
15293
15294            // Reflect the rename internally
15295            codeFile = afterCodeFile;
15296            resourceFile = afterCodeFile;
15297
15298            // Reflect the rename in scanned details
15299            try {
15300                pkg.setCodePath(afterCodeFile.getCanonicalPath());
15301            } catch (IOException e) {
15302                Slog.e(TAG, "Failed to get path: " + afterCodeFile, e);
15303                return false;
15304            }
15305            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15306                    afterCodeFile, pkg.baseCodePath));
15307            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15308                    afterCodeFile, pkg.splitCodePaths));
15309
15310            // Reflect the rename in app info
15311            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15312            pkg.setApplicationInfoCodePath(pkg.codePath);
15313            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15314            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15315            pkg.setApplicationInfoResourcePath(pkg.codePath);
15316            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15317            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15318
15319            return true;
15320        }
15321
15322        int doPostInstall(int status, int uid) {
15323            if (status != PackageManager.INSTALL_SUCCEEDED) {
15324                cleanUp();
15325            }
15326            return status;
15327        }
15328
15329        @Override
15330        String getCodePath() {
15331            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15332        }
15333
15334        @Override
15335        String getResourcePath() {
15336            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15337        }
15338
15339        private boolean cleanUp() {
15340            if (codeFile == null || !codeFile.exists()) {
15341                return false;
15342            }
15343
15344            removeCodePathLI(codeFile);
15345
15346            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15347                resourceFile.delete();
15348            }
15349
15350            return true;
15351        }
15352
15353        void cleanUpResourcesLI() {
15354            // Try enumerating all code paths before deleting
15355            List<String> allCodePaths = Collections.EMPTY_LIST;
15356            if (codeFile != null && codeFile.exists()) {
15357                try {
15358                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15359                    allCodePaths = pkg.getAllCodePaths();
15360                } catch (PackageParserException e) {
15361                    // Ignored; we tried our best
15362                }
15363            }
15364
15365            cleanUp();
15366            removeDexFiles(allCodePaths, instructionSets);
15367        }
15368
15369        boolean doPostDeleteLI(boolean delete) {
15370            // XXX err, shouldn't we respect the delete flag?
15371            cleanUpResourcesLI();
15372            return true;
15373        }
15374    }
15375
15376    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15377            PackageManagerException {
15378        if (copyRet < 0) {
15379            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15380                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15381                throw new PackageManagerException(copyRet, message);
15382            }
15383        }
15384    }
15385
15386    /**
15387     * Extract the StorageManagerService "container ID" from the full code path of an
15388     * .apk.
15389     */
15390    static String cidFromCodePath(String fullCodePath) {
15391        int eidx = fullCodePath.lastIndexOf("/");
15392        String subStr1 = fullCodePath.substring(0, eidx);
15393        int sidx = subStr1.lastIndexOf("/");
15394        return subStr1.substring(sidx+1, eidx);
15395    }
15396
15397    /**
15398     * Logic to handle movement of existing installed applications.
15399     */
15400    class MoveInstallArgs extends InstallArgs {
15401        private File codeFile;
15402        private File resourceFile;
15403
15404        /** New install */
15405        MoveInstallArgs(InstallParams params) {
15406            super(params.origin, params.move, params.observer, params.installFlags,
15407                    params.installerPackageName, params.volumeUuid,
15408                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15409                    params.grantedRuntimePermissions,
15410                    params.traceMethod, params.traceCookie, params.certificates,
15411                    params.installReason);
15412        }
15413
15414        int copyApk(IMediaContainerService imcs, boolean temp) {
15415            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15416                    + move.fromUuid + " to " + move.toUuid);
15417            synchronized (mInstaller) {
15418                try {
15419                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15420                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15421                } catch (InstallerException e) {
15422                    Slog.w(TAG, "Failed to move app", e);
15423                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15424                }
15425            }
15426
15427            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15428            resourceFile = codeFile;
15429            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15430
15431            return PackageManager.INSTALL_SUCCEEDED;
15432        }
15433
15434        int doPreInstall(int status) {
15435            if (status != PackageManager.INSTALL_SUCCEEDED) {
15436                cleanUp(move.toUuid);
15437            }
15438            return status;
15439        }
15440
15441        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15442            if (status != PackageManager.INSTALL_SUCCEEDED) {
15443                cleanUp(move.toUuid);
15444                return false;
15445            }
15446
15447            // Reflect the move in app info
15448            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15449            pkg.setApplicationInfoCodePath(pkg.codePath);
15450            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15451            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15452            pkg.setApplicationInfoResourcePath(pkg.codePath);
15453            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15454            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15455
15456            return true;
15457        }
15458
15459        int doPostInstall(int status, int uid) {
15460            if (status == PackageManager.INSTALL_SUCCEEDED) {
15461                cleanUp(move.fromUuid);
15462            } else {
15463                cleanUp(move.toUuid);
15464            }
15465            return status;
15466        }
15467
15468        @Override
15469        String getCodePath() {
15470            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15471        }
15472
15473        @Override
15474        String getResourcePath() {
15475            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15476        }
15477
15478        private boolean cleanUp(String volumeUuid) {
15479            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15480                    move.dataAppName);
15481            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15482            final int[] userIds = sUserManager.getUserIds();
15483            synchronized (mInstallLock) {
15484                // Clean up both app data and code
15485                // All package moves are frozen until finished
15486                for (int userId : userIds) {
15487                    try {
15488                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15489                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15490                    } catch (InstallerException e) {
15491                        Slog.w(TAG, String.valueOf(e));
15492                    }
15493                }
15494                removeCodePathLI(codeFile);
15495            }
15496            return true;
15497        }
15498
15499        void cleanUpResourcesLI() {
15500            throw new UnsupportedOperationException();
15501        }
15502
15503        boolean doPostDeleteLI(boolean delete) {
15504            throw new UnsupportedOperationException();
15505        }
15506    }
15507
15508    static String getAsecPackageName(String packageCid) {
15509        int idx = packageCid.lastIndexOf("-");
15510        if (idx == -1) {
15511            return packageCid;
15512        }
15513        return packageCid.substring(0, idx);
15514    }
15515
15516    // Utility method used to create code paths based on package name and available index.
15517    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15518        String idxStr = "";
15519        int idx = 1;
15520        // Fall back to default value of idx=1 if prefix is not
15521        // part of oldCodePath
15522        if (oldCodePath != null) {
15523            String subStr = oldCodePath;
15524            // Drop the suffix right away
15525            if (suffix != null && subStr.endsWith(suffix)) {
15526                subStr = subStr.substring(0, subStr.length() - suffix.length());
15527            }
15528            // If oldCodePath already contains prefix find out the
15529            // ending index to either increment or decrement.
15530            int sidx = subStr.lastIndexOf(prefix);
15531            if (sidx != -1) {
15532                subStr = subStr.substring(sidx + prefix.length());
15533                if (subStr != null) {
15534                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15535                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15536                    }
15537                    try {
15538                        idx = Integer.parseInt(subStr);
15539                        if (idx <= 1) {
15540                            idx++;
15541                        } else {
15542                            idx--;
15543                        }
15544                    } catch(NumberFormatException e) {
15545                    }
15546                }
15547            }
15548        }
15549        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15550        return prefix + idxStr;
15551    }
15552
15553    private File getNextCodePath(File targetDir, String packageName) {
15554        File result;
15555        SecureRandom random = new SecureRandom();
15556        byte[] bytes = new byte[16];
15557        do {
15558            random.nextBytes(bytes);
15559            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15560            result = new File(targetDir, packageName + "-" + suffix);
15561        } while (result.exists());
15562        return result;
15563    }
15564
15565    // Utility method that returns the relative package path with respect
15566    // to the installation directory. Like say for /data/data/com.test-1.apk
15567    // string com.test-1 is returned.
15568    static String deriveCodePathName(String codePath) {
15569        if (codePath == null) {
15570            return null;
15571        }
15572        final File codeFile = new File(codePath);
15573        final String name = codeFile.getName();
15574        if (codeFile.isDirectory()) {
15575            return name;
15576        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15577            final int lastDot = name.lastIndexOf('.');
15578            return name.substring(0, lastDot);
15579        } else {
15580            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15581            return null;
15582        }
15583    }
15584
15585    static class PackageInstalledInfo {
15586        String name;
15587        int uid;
15588        // The set of users that originally had this package installed.
15589        int[] origUsers;
15590        // The set of users that now have this package installed.
15591        int[] newUsers;
15592        PackageParser.Package pkg;
15593        int returnCode;
15594        String returnMsg;
15595        String installerPackageName;
15596        PackageRemovedInfo removedInfo;
15597        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15598
15599        public void setError(int code, String msg) {
15600            setReturnCode(code);
15601            setReturnMessage(msg);
15602            Slog.w(TAG, msg);
15603        }
15604
15605        public void setError(String msg, PackageParserException e) {
15606            setReturnCode(e.error);
15607            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15608            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15609            for (int i = 0; i < childCount; i++) {
15610                addedChildPackages.valueAt(i).setError(msg, e);
15611            }
15612            Slog.w(TAG, msg, e);
15613        }
15614
15615        public void setError(String msg, PackageManagerException e) {
15616            returnCode = e.error;
15617            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15618            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15619            for (int i = 0; i < childCount; i++) {
15620                addedChildPackages.valueAt(i).setError(msg, e);
15621            }
15622            Slog.w(TAG, msg, e);
15623        }
15624
15625        public void setReturnCode(int returnCode) {
15626            this.returnCode = returnCode;
15627            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15628            for (int i = 0; i < childCount; i++) {
15629                addedChildPackages.valueAt(i).returnCode = returnCode;
15630            }
15631        }
15632
15633        private void setReturnMessage(String returnMsg) {
15634            this.returnMsg = returnMsg;
15635            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15636            for (int i = 0; i < childCount; i++) {
15637                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15638            }
15639        }
15640
15641        // In some error cases we want to convey more info back to the observer
15642        String origPackage;
15643        String origPermission;
15644    }
15645
15646    /*
15647     * Install a non-existing package.
15648     */
15649    private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
15650            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
15651            String volumeUuid, PackageInstalledInfo res, int installReason) {
15652        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15653
15654        // Remember this for later, in case we need to rollback this install
15655        String pkgName = pkg.packageName;
15656
15657        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15658
15659        synchronized(mPackages) {
15660            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15661            if (renamedPackage != null) {
15662                // A package with the same name is already installed, though
15663                // it has been renamed to an older name.  The package we
15664                // are trying to install should be installed as an update to
15665                // the existing one, but that has not been requested, so bail.
15666                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15667                        + " without first uninstalling package running as "
15668                        + renamedPackage);
15669                return;
15670            }
15671            if (mPackages.containsKey(pkgName)) {
15672                // Don't allow installation over an existing package with the same name.
15673                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15674                        + " without first uninstalling.");
15675                return;
15676            }
15677        }
15678
15679        try {
15680            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
15681                    System.currentTimeMillis(), user);
15682
15683            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15684
15685            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15686                prepareAppDataAfterInstallLIF(newPackage);
15687
15688            } else {
15689                // Remove package from internal structures, but keep around any
15690                // data that might have already existed
15691                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15692                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15693            }
15694        } catch (PackageManagerException e) {
15695            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15696        }
15697
15698        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15699    }
15700
15701    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15702        try (DigestInputStream digestStream =
15703                new DigestInputStream(new FileInputStream(file), digest)) {
15704            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15705        }
15706    }
15707
15708    private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
15709            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
15710            PackageInstalledInfo res, int installReason) {
15711        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15712
15713        final PackageParser.Package oldPackage;
15714        final PackageSetting ps;
15715        final String pkgName = pkg.packageName;
15716        final int[] allUsers;
15717        final int[] installedUsers;
15718
15719        synchronized(mPackages) {
15720            oldPackage = mPackages.get(pkgName);
15721            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15722
15723            // don't allow upgrade to target a release SDK from a pre-release SDK
15724            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15725                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15726            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15727                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15728            if (oldTargetsPreRelease
15729                    && !newTargetsPreRelease
15730                    && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
15731                Slog.w(TAG, "Can't install package targeting released sdk");
15732                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
15733                return;
15734            }
15735
15736            ps = mSettings.mPackages.get(pkgName);
15737
15738            // verify signatures are valid
15739            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
15740            if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) {
15741                if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) {
15742                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15743                            "New package not signed by keys specified by upgrade-keysets: "
15744                                    + pkgName);
15745                    return;
15746                }
15747            } else {
15748                // default to original signature matching
15749                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
15750                        != PackageManager.SIGNATURE_MATCH) {
15751                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15752                            "New package has a different signature: " + pkgName);
15753                    return;
15754                }
15755            }
15756
15757            // don't allow a system upgrade unless the upgrade hash matches
15758            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) {
15759                byte[] digestBytes = null;
15760                try {
15761                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
15762                    updateDigest(digest, new File(pkg.baseCodePath));
15763                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
15764                        for (String path : pkg.splitCodePaths) {
15765                            updateDigest(digest, new File(path));
15766                        }
15767                    }
15768                    digestBytes = digest.digest();
15769                } catch (NoSuchAlgorithmException | IOException e) {
15770                    res.setError(INSTALL_FAILED_INVALID_APK,
15771                            "Could not compute hash: " + pkgName);
15772                    return;
15773                }
15774                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
15775                    res.setError(INSTALL_FAILED_INVALID_APK,
15776                            "New package fails restrict-update check: " + pkgName);
15777                    return;
15778                }
15779                // retain upgrade restriction
15780                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
15781            }
15782
15783            // Check for shared user id changes
15784            String invalidPackageName =
15785                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
15786            if (invalidPackageName != null) {
15787                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
15788                        "Package " + invalidPackageName + " tried to change user "
15789                                + oldPackage.mSharedUserId);
15790                return;
15791            }
15792
15793            // check if the new package supports all of the abis which the old package supports
15794            boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null;
15795            boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null;
15796            if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) {
15797                res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15798                        "Update to package " + pkgName + " doesn't support multi arch");
15799                return;
15800            }
15801
15802            // In case of rollback, remember per-user/profile install state
15803            allUsers = sUserManager.getUserIds();
15804            installedUsers = ps.queryInstalledUsers(allUsers, true);
15805
15806            // don't allow an upgrade from full to ephemeral
15807            if (isInstantApp) {
15808                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
15809                    for (int currentUser : allUsers) {
15810                        if (!ps.getInstantApp(currentUser)) {
15811                            // can't downgrade from full to instant
15812                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
15813                                    + " for user: " + currentUser);
15814                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15815                            return;
15816                        }
15817                    }
15818                } else if (!ps.getInstantApp(user.getIdentifier())) {
15819                    // can't downgrade from full to instant
15820                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
15821                            + " for user: " + user.getIdentifier());
15822                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15823                    return;
15824                }
15825            }
15826        }
15827
15828        // Update what is removed
15829        res.removedInfo = new PackageRemovedInfo(this);
15830        res.removedInfo.uid = oldPackage.applicationInfo.uid;
15831        res.removedInfo.removedPackage = oldPackage.packageName;
15832        res.removedInfo.installerPackageName = ps.installerPackageName;
15833        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
15834        res.removedInfo.isUpdate = true;
15835        res.removedInfo.origUsers = installedUsers;
15836        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
15837        for (int i = 0; i < installedUsers.length; i++) {
15838            final int userId = installedUsers[i];
15839            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
15840        }
15841
15842        final int childCount = (oldPackage.childPackages != null)
15843                ? oldPackage.childPackages.size() : 0;
15844        for (int i = 0; i < childCount; i++) {
15845            boolean childPackageUpdated = false;
15846            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
15847            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15848            if (res.addedChildPackages != null) {
15849                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15850                if (childRes != null) {
15851                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
15852                    childRes.removedInfo.removedPackage = childPkg.packageName;
15853                    if (childPs != null) {
15854                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
15855                    }
15856                    childRes.removedInfo.isUpdate = true;
15857                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
15858                    childPackageUpdated = true;
15859                }
15860            }
15861            if (!childPackageUpdated) {
15862                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
15863                childRemovedRes.removedPackage = childPkg.packageName;
15864                if (childPs != null) {
15865                    childRemovedRes.installerPackageName = childPs.installerPackageName;
15866                }
15867                childRemovedRes.isUpdate = false;
15868                childRemovedRes.dataRemoved = true;
15869                synchronized (mPackages) {
15870                    if (childPs != null) {
15871                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
15872                    }
15873                }
15874                if (res.removedInfo.removedChildPackages == null) {
15875                    res.removedInfo.removedChildPackages = new ArrayMap<>();
15876                }
15877                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
15878            }
15879        }
15880
15881        boolean sysPkg = (isSystemApp(oldPackage));
15882        if (sysPkg) {
15883            // Set the system/privileged/oem/vendor flags as needed
15884            final boolean privileged =
15885                    (oldPackage.applicationInfo.privateFlags
15886                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15887            final boolean oem =
15888                    (oldPackage.applicationInfo.privateFlags
15889                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
15890            final boolean vendor =
15891                    (oldPackage.applicationInfo.privateFlags
15892                            & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
15893            final @ParseFlags int systemParseFlags = parseFlags;
15894            final @ScanFlags int systemScanFlags = scanFlags
15895                    | SCAN_AS_SYSTEM
15896                    | (privileged ? SCAN_AS_PRIVILEGED : 0)
15897                    | (oem ? SCAN_AS_OEM : 0)
15898                    | (vendor ? SCAN_AS_VENDOR : 0);
15899
15900            replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags,
15901                    user, allUsers, installerPackageName, res, installReason);
15902        } else {
15903            replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags,
15904                    user, allUsers, installerPackageName, res, installReason);
15905        }
15906    }
15907
15908    @Override
15909    public List<String> getPreviousCodePaths(String packageName) {
15910        final int callingUid = Binder.getCallingUid();
15911        final List<String> result = new ArrayList<>();
15912        if (getInstantAppPackageName(callingUid) != null) {
15913            return result;
15914        }
15915        final PackageSetting ps = mSettings.mPackages.get(packageName);
15916        if (ps != null
15917                && ps.oldCodePaths != null
15918                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15919            result.addAll(ps.oldCodePaths);
15920        }
15921        return result;
15922    }
15923
15924    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
15925            PackageParser.Package pkg, final @ParseFlags int parseFlags,
15926            final @ScanFlags int scanFlags, UserHandle user, int[] allUsers,
15927            String installerPackageName, PackageInstalledInfo res, int installReason) {
15928        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
15929                + deletedPackage);
15930
15931        String pkgName = deletedPackage.packageName;
15932        boolean deletedPkg = true;
15933        boolean addedPkg = false;
15934        boolean updatedSettings = false;
15935        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
15936        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
15937                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
15938
15939        final long origUpdateTime = (pkg.mExtras != null)
15940                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
15941
15942        // First delete the existing package while retaining the data directory
15943        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15944                res.removedInfo, true, pkg)) {
15945            // If the existing package wasn't successfully deleted
15946            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
15947            deletedPkg = false;
15948        } else {
15949            // Successfully deleted the old package; proceed with replace.
15950
15951            // If deleted package lived in a container, give users a chance to
15952            // relinquish resources before killing.
15953            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
15954                if (DEBUG_INSTALL) {
15955                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
15956                }
15957                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
15958                final ArrayList<String> pkgList = new ArrayList<String>(1);
15959                pkgList.add(deletedPackage.applicationInfo.packageName);
15960                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
15961            }
15962
15963            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
15964                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
15965            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
15966
15967            try {
15968                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
15969                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
15970                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
15971                        installReason);
15972
15973                // Update the in-memory copy of the previous code paths.
15974                PackageSetting ps = mSettings.mPackages.get(pkgName);
15975                if (!killApp) {
15976                    if (ps.oldCodePaths == null) {
15977                        ps.oldCodePaths = new ArraySet<>();
15978                    }
15979                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
15980                    if (deletedPackage.splitCodePaths != null) {
15981                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
15982                    }
15983                } else {
15984                    ps.oldCodePaths = null;
15985                }
15986                if (ps.childPackageNames != null) {
15987                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
15988                        final String childPkgName = ps.childPackageNames.get(i);
15989                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
15990                        childPs.oldCodePaths = ps.oldCodePaths;
15991                    }
15992                }
15993                // set instant app status, but, only if it's explicitly specified
15994                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15995                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
15996                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
15997                prepareAppDataAfterInstallLIF(newPackage);
15998                addedPkg = true;
15999                mDexManager.notifyPackageUpdated(newPackage.packageName,
16000                        newPackage.baseCodePath, newPackage.splitCodePaths);
16001            } catch (PackageManagerException e) {
16002                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16003            }
16004        }
16005
16006        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16007            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16008
16009            // Revert all internal state mutations and added folders for the failed install
16010            if (addedPkg) {
16011                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16012                        res.removedInfo, true, null);
16013            }
16014
16015            // Restore the old package
16016            if (deletedPkg) {
16017                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16018                File restoreFile = new File(deletedPackage.codePath);
16019                // Parse old package
16020                boolean oldExternal = isExternal(deletedPackage);
16021                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16022                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16023                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16024                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16025                try {
16026                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16027                            null);
16028                } catch (PackageManagerException e) {
16029                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16030                            + e.getMessage());
16031                    return;
16032                }
16033
16034                synchronized (mPackages) {
16035                    // Ensure the installer package name up to date
16036                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16037
16038                    // Update permissions for restored package
16039                    mPermissionManager.updatePermissions(
16040                            deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16041                            mPermissionCallback);
16042
16043                    mSettings.writeLPr();
16044                }
16045
16046                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16047            }
16048        } else {
16049            synchronized (mPackages) {
16050                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16051                if (ps != null) {
16052                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16053                    if (res.removedInfo.removedChildPackages != null) {
16054                        final int childCount = res.removedInfo.removedChildPackages.size();
16055                        // Iterate in reverse as we may modify the collection
16056                        for (int i = childCount - 1; i >= 0; i--) {
16057                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16058                            if (res.addedChildPackages.containsKey(childPackageName)) {
16059                                res.removedInfo.removedChildPackages.removeAt(i);
16060                            } else {
16061                                PackageRemovedInfo childInfo = res.removedInfo
16062                                        .removedChildPackages.valueAt(i);
16063                                childInfo.removedForAllUsers = mPackages.get(
16064                                        childInfo.removedPackage) == null;
16065                            }
16066                        }
16067                    }
16068                }
16069            }
16070        }
16071    }
16072
16073    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16074            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16075            final @ScanFlags int scanFlags, UserHandle user,
16076            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16077            int installReason) {
16078        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16079                + ", old=" + deletedPackage);
16080
16081        final boolean disabledSystem;
16082
16083        // Remove existing system package
16084        removePackageLI(deletedPackage, true);
16085
16086        synchronized (mPackages) {
16087            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16088        }
16089        if (!disabledSystem) {
16090            // We didn't need to disable the .apk as a current system package,
16091            // which means we are replacing another update that is already
16092            // installed.  We need to make sure to delete the older one's .apk.
16093            res.removedInfo.args = createInstallArgsForExisting(0,
16094                    deletedPackage.applicationInfo.getCodePath(),
16095                    deletedPackage.applicationInfo.getResourcePath(),
16096                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16097        } else {
16098            res.removedInfo.args = null;
16099        }
16100
16101        // Successfully disabled the old package. Now proceed with re-installation
16102        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16103                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16104        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16105
16106        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16107        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16108                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16109
16110        PackageParser.Package newPackage = null;
16111        try {
16112            // Add the package to the internal data structures
16113            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
16114
16115            // Set the update and install times
16116            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16117            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16118                    System.currentTimeMillis());
16119
16120            // Update the package dynamic state if succeeded
16121            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16122                // Now that the install succeeded make sure we remove data
16123                // directories for any child package the update removed.
16124                final int deletedChildCount = (deletedPackage.childPackages != null)
16125                        ? deletedPackage.childPackages.size() : 0;
16126                final int newChildCount = (newPackage.childPackages != null)
16127                        ? newPackage.childPackages.size() : 0;
16128                for (int i = 0; i < deletedChildCount; i++) {
16129                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16130                    boolean childPackageDeleted = true;
16131                    for (int j = 0; j < newChildCount; j++) {
16132                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16133                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16134                            childPackageDeleted = false;
16135                            break;
16136                        }
16137                    }
16138                    if (childPackageDeleted) {
16139                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16140                                deletedChildPkg.packageName);
16141                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16142                            PackageRemovedInfo removedChildRes = res.removedInfo
16143                                    .removedChildPackages.get(deletedChildPkg.packageName);
16144                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16145                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16146                        }
16147                    }
16148                }
16149
16150                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16151                        installReason);
16152                prepareAppDataAfterInstallLIF(newPackage);
16153
16154                mDexManager.notifyPackageUpdated(newPackage.packageName,
16155                            newPackage.baseCodePath, newPackage.splitCodePaths);
16156            }
16157        } catch (PackageManagerException e) {
16158            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16159            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16160        }
16161
16162        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16163            // Re installation failed. Restore old information
16164            // Remove new pkg information
16165            if (newPackage != null) {
16166                removeInstalledPackageLI(newPackage, true);
16167            }
16168            // Add back the old system package
16169            try {
16170                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16171            } catch (PackageManagerException e) {
16172                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16173            }
16174
16175            synchronized (mPackages) {
16176                if (disabledSystem) {
16177                    enableSystemPackageLPw(deletedPackage);
16178                }
16179
16180                // Ensure the installer package name up to date
16181                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16182
16183                // Update permissions for restored package
16184                mPermissionManager.updatePermissions(
16185                        deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16186                        mPermissionCallback);
16187
16188                mSettings.writeLPr();
16189            }
16190
16191            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16192                    + " after failed upgrade");
16193        }
16194    }
16195
16196    /**
16197     * Checks whether the parent or any of the child packages have a change shared
16198     * user. For a package to be a valid update the shred users of the parent and
16199     * the children should match. We may later support changing child shared users.
16200     * @param oldPkg The updated package.
16201     * @param newPkg The update package.
16202     * @return The shared user that change between the versions.
16203     */
16204    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16205            PackageParser.Package newPkg) {
16206        // Check parent shared user
16207        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16208            return newPkg.packageName;
16209        }
16210        // Check child shared users
16211        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16212        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16213        for (int i = 0; i < newChildCount; i++) {
16214            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16215            // If this child was present, did it have the same shared user?
16216            for (int j = 0; j < oldChildCount; j++) {
16217                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16218                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16219                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16220                    return newChildPkg.packageName;
16221                }
16222            }
16223        }
16224        return null;
16225    }
16226
16227    private void removeNativeBinariesLI(PackageSetting ps) {
16228        // Remove the lib path for the parent package
16229        if (ps != null) {
16230            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16231            // Remove the lib path for the child packages
16232            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16233            for (int i = 0; i < childCount; i++) {
16234                PackageSetting childPs = null;
16235                synchronized (mPackages) {
16236                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16237                }
16238                if (childPs != null) {
16239                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16240                            .legacyNativeLibraryPathString);
16241                }
16242            }
16243        }
16244    }
16245
16246    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16247        // Enable the parent package
16248        mSettings.enableSystemPackageLPw(pkg.packageName);
16249        // Enable the child packages
16250        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16251        for (int i = 0; i < childCount; i++) {
16252            PackageParser.Package childPkg = pkg.childPackages.get(i);
16253            mSettings.enableSystemPackageLPw(childPkg.packageName);
16254        }
16255    }
16256
16257    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16258            PackageParser.Package newPkg) {
16259        // Disable the parent package (parent always replaced)
16260        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16261        // Disable the child packages
16262        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16263        for (int i = 0; i < childCount; i++) {
16264            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16265            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16266            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16267        }
16268        return disabled;
16269    }
16270
16271    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16272            String installerPackageName) {
16273        // Enable the parent package
16274        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16275        // Enable the child packages
16276        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16277        for (int i = 0; i < childCount; i++) {
16278            PackageParser.Package childPkg = pkg.childPackages.get(i);
16279            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16280        }
16281    }
16282
16283    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16284            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16285        // Update the parent package setting
16286        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16287                res, user, installReason);
16288        // Update the child packages setting
16289        final int childCount = (newPackage.childPackages != null)
16290                ? newPackage.childPackages.size() : 0;
16291        for (int i = 0; i < childCount; i++) {
16292            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16293            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16294            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16295                    childRes.origUsers, childRes, user, installReason);
16296        }
16297    }
16298
16299    private void updateSettingsInternalLI(PackageParser.Package pkg,
16300            String installerPackageName, int[] allUsers, int[] installedForUsers,
16301            PackageInstalledInfo res, UserHandle user, int installReason) {
16302        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16303
16304        String pkgName = pkg.packageName;
16305        synchronized (mPackages) {
16306            //write settings. the installStatus will be incomplete at this stage.
16307            //note that the new package setting would have already been
16308            //added to mPackages. It hasn't been persisted yet.
16309            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16310            // TODO: Remove this write? It's also written at the end of this method
16311            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16312            mSettings.writeLPr();
16313            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16314        }
16315
16316        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath);
16317        synchronized (mPackages) {
16318// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions
16319            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
16320                    mPermissionCallback);
16321            // For system-bundled packages, we assume that installing an upgraded version
16322            // of the package implies that the user actually wants to run that new code,
16323            // so we enable the package.
16324            PackageSetting ps = mSettings.mPackages.get(pkgName);
16325            final int userId = user.getIdentifier();
16326            if (ps != null) {
16327                if (isSystemApp(pkg)) {
16328                    if (DEBUG_INSTALL) {
16329                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16330                    }
16331                    // Enable system package for requested users
16332                    if (res.origUsers != null) {
16333                        for (int origUserId : res.origUsers) {
16334                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16335                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16336                                        origUserId, installerPackageName);
16337                            }
16338                        }
16339                    }
16340                    // Also convey the prior install/uninstall state
16341                    if (allUsers != null && installedForUsers != null) {
16342                        for (int currentUserId : allUsers) {
16343                            final boolean installed = ArrayUtils.contains(
16344                                    installedForUsers, currentUserId);
16345                            if (DEBUG_INSTALL) {
16346                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16347                            }
16348                            ps.setInstalled(installed, currentUserId);
16349                        }
16350                        // these install state changes will be persisted in the
16351                        // upcoming call to mSettings.writeLPr().
16352                    }
16353                }
16354                // It's implied that when a user requests installation, they want the app to be
16355                // installed and enabled.
16356                if (userId != UserHandle.USER_ALL) {
16357                    ps.setInstalled(true, userId);
16358                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16359                }
16360
16361                // When replacing an existing package, preserve the original install reason for all
16362                // users that had the package installed before.
16363                final Set<Integer> previousUserIds = new ArraySet<>();
16364                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16365                    final int installReasonCount = res.removedInfo.installReasons.size();
16366                    for (int i = 0; i < installReasonCount; i++) {
16367                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16368                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16369                        ps.setInstallReason(previousInstallReason, previousUserId);
16370                        previousUserIds.add(previousUserId);
16371                    }
16372                }
16373
16374                // Set install reason for users that are having the package newly installed.
16375                if (userId == UserHandle.USER_ALL) {
16376                    for (int currentUserId : sUserManager.getUserIds()) {
16377                        if (!previousUserIds.contains(currentUserId)) {
16378                            ps.setInstallReason(installReason, currentUserId);
16379                        }
16380                    }
16381                } else if (!previousUserIds.contains(userId)) {
16382                    ps.setInstallReason(installReason, userId);
16383                }
16384                mSettings.writeKernelMappingLPr(ps);
16385            }
16386            res.name = pkgName;
16387            res.uid = pkg.applicationInfo.uid;
16388            res.pkg = pkg;
16389            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16390            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16391            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16392            //to update install status
16393            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16394            mSettings.writeLPr();
16395            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16396        }
16397
16398        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16399    }
16400
16401    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16402        try {
16403            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16404            installPackageLI(args, res);
16405        } finally {
16406            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16407        }
16408    }
16409
16410    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16411        final int installFlags = args.installFlags;
16412        final String installerPackageName = args.installerPackageName;
16413        final String volumeUuid = args.volumeUuid;
16414        final File tmpPackageFile = new File(args.getCodePath());
16415        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16416        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16417                || (args.volumeUuid != null));
16418        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16419        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16420        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16421        final boolean virtualPreload =
16422                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
16423        boolean replace = false;
16424        @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16425        if (args.move != null) {
16426            // moving a complete application; perform an initial scan on the new install location
16427            scanFlags |= SCAN_INITIAL;
16428        }
16429        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16430            scanFlags |= SCAN_DONT_KILL_APP;
16431        }
16432        if (instantApp) {
16433            scanFlags |= SCAN_AS_INSTANT_APP;
16434        }
16435        if (fullApp) {
16436            scanFlags |= SCAN_AS_FULL_APP;
16437        }
16438        if (virtualPreload) {
16439            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
16440        }
16441
16442        // Result object to be returned
16443        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16444        res.installerPackageName = installerPackageName;
16445
16446        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16447
16448        // Sanity check
16449        if (instantApp && (forwardLocked || onExternal)) {
16450            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16451                    + " external=" + onExternal);
16452            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16453            return;
16454        }
16455
16456        // Retrieve PackageSettings and parse package
16457        @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16458                | PackageParser.PARSE_ENFORCE_CODE
16459                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16460                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16461                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
16462                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16463        PackageParser pp = new PackageParser();
16464        pp.setSeparateProcesses(mSeparateProcesses);
16465        pp.setDisplayMetrics(mMetrics);
16466        pp.setCallback(mPackageParserCallback);
16467
16468        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16469        final PackageParser.Package pkg;
16470        try {
16471            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16472        } catch (PackageParserException e) {
16473            res.setError("Failed parse during installPackageLI", e);
16474            return;
16475        } finally {
16476            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16477        }
16478
16479        // App targetSdkVersion is below min supported version
16480        if (!forceSdk && pkg.applicationInfo.isTargetingDeprecatedSdkVersion()) {
16481            Slog.w(TAG, "App " + pkg.packageName + " targets deprecated sdk");
16482
16483            res.setError(INSTALL_FAILED_NEWER_SDK,
16484                    "App is targeting deprecated sdk (targetSdkVersion should be at least "
16485                    + Build.VERSION.MIN_SUPPORTED_TARGET_SDK_INT + ").");
16486            return;
16487        }
16488
16489        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
16490        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
16491            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
16492            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16493                    "Instant app package must target O");
16494            return;
16495        }
16496        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
16497            Slog.w(TAG, "Instant app package " + pkg.packageName
16498                    + " does not target targetSandboxVersion 2");
16499            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16500                    "Instant app package must use targetSanboxVersion 2");
16501            return;
16502        }
16503
16504        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16505            // Static shared libraries have synthetic package names
16506            renameStaticSharedLibraryPackage(pkg);
16507
16508            // No static shared libs on external storage
16509            if (onExternal) {
16510                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16511                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16512                        "Packages declaring static-shared libs cannot be updated");
16513                return;
16514            }
16515        }
16516
16517        // If we are installing a clustered package add results for the children
16518        if (pkg.childPackages != null) {
16519            synchronized (mPackages) {
16520                final int childCount = pkg.childPackages.size();
16521                for (int i = 0; i < childCount; i++) {
16522                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16523                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16524                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16525                    childRes.pkg = childPkg;
16526                    childRes.name = childPkg.packageName;
16527                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16528                    if (childPs != null) {
16529                        childRes.origUsers = childPs.queryInstalledUsers(
16530                                sUserManager.getUserIds(), true);
16531                    }
16532                    if ((mPackages.containsKey(childPkg.packageName))) {
16533                        childRes.removedInfo = new PackageRemovedInfo(this);
16534                        childRes.removedInfo.removedPackage = childPkg.packageName;
16535                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16536                    }
16537                    if (res.addedChildPackages == null) {
16538                        res.addedChildPackages = new ArrayMap<>();
16539                    }
16540                    res.addedChildPackages.put(childPkg.packageName, childRes);
16541                }
16542            }
16543        }
16544
16545        // If package doesn't declare API override, mark that we have an install
16546        // time CPU ABI override.
16547        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16548            pkg.cpuAbiOverride = args.abiOverride;
16549        }
16550
16551        String pkgName = res.name = pkg.packageName;
16552        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16553            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16554                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16555                return;
16556            }
16557        }
16558
16559        try {
16560            // either use what we've been given or parse directly from the APK
16561            if (args.certificates != null) {
16562                try {
16563                    PackageParser.populateCertificates(pkg, args.certificates);
16564                } catch (PackageParserException e) {
16565                    // there was something wrong with the certificates we were given;
16566                    // try to pull them from the APK
16567                    PackageParser.collectCertificates(pkg, parseFlags);
16568                }
16569            } else {
16570                PackageParser.collectCertificates(pkg, parseFlags);
16571            }
16572        } catch (PackageParserException e) {
16573            res.setError("Failed collect during installPackageLI", e);
16574            return;
16575        }
16576
16577        // Get rid of all references to package scan path via parser.
16578        pp = null;
16579        String oldCodePath = null;
16580        boolean systemApp = false;
16581        synchronized (mPackages) {
16582            // Check if installing already existing package
16583            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16584                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16585                if (pkg.mOriginalPackages != null
16586                        && pkg.mOriginalPackages.contains(oldName)
16587                        && mPackages.containsKey(oldName)) {
16588                    // This package is derived from an original package,
16589                    // and this device has been updating from that original
16590                    // name.  We must continue using the original name, so
16591                    // rename the new package here.
16592                    pkg.setPackageName(oldName);
16593                    pkgName = pkg.packageName;
16594                    replace = true;
16595                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16596                            + oldName + " pkgName=" + pkgName);
16597                } else if (mPackages.containsKey(pkgName)) {
16598                    // This package, under its official name, already exists
16599                    // on the device; we should replace it.
16600                    replace = true;
16601                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16602                }
16603
16604                // Child packages are installed through the parent package
16605                if (pkg.parentPackage != null) {
16606                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16607                            "Package " + pkg.packageName + " is child of package "
16608                                    + pkg.parentPackage.parentPackage + ". Child packages "
16609                                    + "can be updated only through the parent package.");
16610                    return;
16611                }
16612
16613                if (replace) {
16614                    // Prevent apps opting out from runtime permissions
16615                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16616                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16617                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16618                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16619                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16620                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16621                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16622                                        + " doesn't support runtime permissions but the old"
16623                                        + " target SDK " + oldTargetSdk + " does.");
16624                        return;
16625                    }
16626                    // Prevent persistent apps from being updated
16627                    if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) {
16628                        res.setError(PackageManager.INSTALL_FAILED_INVALID_APK,
16629                                "Package " + oldPackage.packageName + " is a persistent app. "
16630                                        + "Persistent apps are not updateable.");
16631                        return;
16632                    }
16633                    // Prevent apps from downgrading their targetSandbox.
16634                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
16635                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
16636                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
16637                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16638                                "Package " + pkg.packageName + " new target sandbox "
16639                                + newTargetSandbox + " is incompatible with the previous value of"
16640                                + oldTargetSandbox + ".");
16641                        return;
16642                    }
16643
16644                    // Prevent installing of child packages
16645                    if (oldPackage.parentPackage != null) {
16646                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16647                                "Package " + pkg.packageName + " is child of package "
16648                                        + oldPackage.parentPackage + ". Child packages "
16649                                        + "can be updated only through the parent package.");
16650                        return;
16651                    }
16652                }
16653            }
16654
16655            PackageSetting ps = mSettings.mPackages.get(pkgName);
16656            if (ps != null) {
16657                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16658
16659                // Static shared libs have same package with different versions where
16660                // we internally use a synthetic package name to allow multiple versions
16661                // of the same package, therefore we need to compare signatures against
16662                // the package setting for the latest library version.
16663                PackageSetting signatureCheckPs = ps;
16664                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16665                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16666                    if (libraryEntry != null) {
16667                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16668                    }
16669                }
16670
16671                // Quick sanity check that we're signed correctly if updating;
16672                // we'll check this again later when scanning, but we want to
16673                // bail early here before tripping over redefined permissions.
16674                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16675                if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
16676                    if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
16677                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16678                                + pkg.packageName + " upgrade keys do not match the "
16679                                + "previously installed version");
16680                        return;
16681                    }
16682                } else {
16683                    try {
16684                        final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
16685                        final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
16686                        final boolean compatMatch = verifySignatures(
16687                                signatureCheckPs, pkg.mSignatures, compareCompat, compareRecover);
16688                        // The new KeySets will be re-added later in the scanning process.
16689                        if (compatMatch) {
16690                            synchronized (mPackages) {
16691                                ksms.removeAppKeySetDataLPw(pkg.packageName);
16692                            }
16693                        }
16694                    } catch (PackageManagerException e) {
16695                        res.setError(e.error, e.getMessage());
16696                        return;
16697                    }
16698                }
16699
16700                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
16701                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
16702                    systemApp = (ps.pkg.applicationInfo.flags &
16703                            ApplicationInfo.FLAG_SYSTEM) != 0;
16704                }
16705                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16706            }
16707
16708            int N = pkg.permissions.size();
16709            for (int i = N-1; i >= 0; i--) {
16710                final PackageParser.Permission perm = pkg.permissions.get(i);
16711                final BasePermission bp =
16712                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
16713
16714                // Don't allow anyone but the system to define ephemeral permissions.
16715                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
16716                        && !systemApp) {
16717                    Slog.w(TAG, "Non-System package " + pkg.packageName
16718                            + " attempting to delcare ephemeral permission "
16719                            + perm.info.name + "; Removing ephemeral.");
16720                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
16721                }
16722
16723                // Check whether the newly-scanned package wants to define an already-defined perm
16724                if (bp != null) {
16725                    // If the defining package is signed with our cert, it's okay.  This
16726                    // also includes the "updating the same package" case, of course.
16727                    // "updating same package" could also involve key-rotation.
16728                    final boolean sigsOk;
16729                    final String sourcePackageName = bp.getSourcePackageName();
16730                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
16731                    final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16732                    if (sourcePackageName.equals(pkg.packageName)
16733                            && (ksms.shouldCheckUpgradeKeySetLocked(
16734                                    sourcePackageSetting, scanFlags))) {
16735                        sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg);
16736                    } else {
16737                        sigsOk = compareSignatures(sourcePackageSetting.signatures.mSignatures,
16738                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
16739                    }
16740                    if (!sigsOk) {
16741                        // If the owning package is the system itself, we log but allow
16742                        // install to proceed; we fail the install on all other permission
16743                        // redefinitions.
16744                        if (!sourcePackageName.equals("android")) {
16745                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
16746                                    + pkg.packageName + " attempting to redeclare permission "
16747                                    + perm.info.name + " already owned by " + sourcePackageName);
16748                            res.origPermission = perm.info.name;
16749                            res.origPackage = sourcePackageName;
16750                            return;
16751                        } else {
16752                            Slog.w(TAG, "Package " + pkg.packageName
16753                                    + " attempting to redeclare system permission "
16754                                    + perm.info.name + "; ignoring new declaration");
16755                            pkg.permissions.remove(i);
16756                        }
16757                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16758                        // Prevent apps to change protection level to dangerous from any other
16759                        // type as this would allow a privilege escalation where an app adds a
16760                        // normal/signature permission in other app's group and later redefines
16761                        // it as dangerous leading to the group auto-grant.
16762                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
16763                                == PermissionInfo.PROTECTION_DANGEROUS) {
16764                            if (bp != null && !bp.isRuntime()) {
16765                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
16766                                        + "non-runtime permission " + perm.info.name
16767                                        + " to runtime; keeping old protection level");
16768                                perm.info.protectionLevel = bp.getProtectionLevel();
16769                            }
16770                        }
16771                    }
16772                }
16773            }
16774        }
16775
16776        if (systemApp) {
16777            if (onExternal) {
16778                // Abort update; system app can't be replaced with app on sdcard
16779                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16780                        "Cannot install updates to system apps on sdcard");
16781                return;
16782            } else if (instantApp) {
16783                // Abort update; system app can't be replaced with an instant app
16784                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16785                        "Cannot update a system app with an instant app");
16786                return;
16787            }
16788        }
16789
16790        if (args.move != null) {
16791            // We did an in-place move, so dex is ready to roll
16792            scanFlags |= SCAN_NO_DEX;
16793            scanFlags |= SCAN_MOVE;
16794
16795            synchronized (mPackages) {
16796                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16797                if (ps == null) {
16798                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
16799                            "Missing settings for moved package " + pkgName);
16800                }
16801
16802                // We moved the entire application as-is, so bring over the
16803                // previously derived ABI information.
16804                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
16805                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
16806            }
16807
16808        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
16809            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
16810            scanFlags |= SCAN_NO_DEX;
16811
16812            try {
16813                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
16814                    args.abiOverride : pkg.cpuAbiOverride);
16815                final boolean extractNativeLibs = !pkg.isLibrary();
16816                derivePackageAbi(pkg, abiOverride, extractNativeLibs);
16817            } catch (PackageManagerException pme) {
16818                Slog.e(TAG, "Error deriving application ABI", pme);
16819                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
16820                return;
16821            }
16822
16823            // Shared libraries for the package need to be updated.
16824            synchronized (mPackages) {
16825                try {
16826                    updateSharedLibrariesLPr(pkg, null);
16827                } catch (PackageManagerException e) {
16828                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
16829                }
16830            }
16831        }
16832
16833        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
16834            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
16835            return;
16836        }
16837
16838        if (!instantApp) {
16839            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
16840        } else {
16841            if (DEBUG_DOMAIN_VERIFICATION) {
16842                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
16843            }
16844        }
16845
16846        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
16847                "installPackageLI")) {
16848            if (replace) {
16849                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16850                    // Static libs have a synthetic package name containing the version
16851                    // and cannot be updated as an update would get a new package name,
16852                    // unless this is the exact same version code which is useful for
16853                    // development.
16854                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
16855                    if (existingPkg != null &&
16856                            existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) {
16857                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
16858                                + "static-shared libs cannot be updated");
16859                        return;
16860                    }
16861                }
16862                replacePackageLIF(pkg, parseFlags, scanFlags, args.user,
16863                        installerPackageName, res, args.installReason);
16864            } else {
16865                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
16866                        args.user, installerPackageName, volumeUuid, res, args.installReason);
16867            }
16868        }
16869
16870        // Check whether we need to dexopt the app.
16871        //
16872        // NOTE: it is IMPORTANT to call dexopt:
16873        //   - after doRename which will sync the package data from PackageParser.Package and its
16874        //     corresponding ApplicationInfo.
16875        //   - after installNewPackageLIF or replacePackageLIF which will update result with the
16876        //     uid of the application (pkg.applicationInfo.uid).
16877        //     This update happens in place!
16878        //
16879        // We only need to dexopt if the package meets ALL of the following conditions:
16880        //   1) it is not forward locked.
16881        //   2) it is not on on an external ASEC container.
16882        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
16883        //
16884        // Note that we do not dexopt instant apps by default. dexopt can take some time to
16885        // complete, so we skip this step during installation. Instead, we'll take extra time
16886        // the first time the instant app starts. It's preferred to do it this way to provide
16887        // continuous progress to the useur instead of mysteriously blocking somewhere in the
16888        // middle of running an instant app. The default behaviour can be overridden
16889        // via gservices.
16890        final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED)
16891                && !forwardLocked
16892                && !pkg.applicationInfo.isExternalAsec()
16893                && (!instantApp || Global.getInt(mContext.getContentResolver(),
16894                Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
16895
16896        if (performDexopt) {
16897            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
16898            // Do not run PackageDexOptimizer through the local performDexOpt
16899            // method because `pkg` may not be in `mPackages` yet.
16900            //
16901            // Also, don't fail application installs if the dexopt step fails.
16902            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
16903                    REASON_INSTALL,
16904                    DexoptOptions.DEXOPT_BOOT_COMPLETE);
16905            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
16906                    null /* instructionSets */,
16907                    getOrCreateCompilerPackageStats(pkg),
16908                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
16909                    dexoptOptions);
16910            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16911        }
16912
16913        // Notify BackgroundDexOptService that the package has been changed.
16914        // If this is an update of a package which used to fail to compile,
16915        // BackgroundDexOptService will remove it from its blacklist.
16916        // TODO: Layering violation
16917        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
16918
16919        synchronized (mPackages) {
16920            final PackageSetting ps = mSettings.mPackages.get(pkgName);
16921            if (ps != null) {
16922                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16923                ps.setUpdateAvailable(false /*updateAvailable*/);
16924            }
16925
16926            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16927            for (int i = 0; i < childCount; i++) {
16928                PackageParser.Package childPkg = pkg.childPackages.get(i);
16929                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16930                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16931                if (childPs != null) {
16932                    childRes.newUsers = childPs.queryInstalledUsers(
16933                            sUserManager.getUserIds(), true);
16934                }
16935            }
16936
16937            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16938                updateSequenceNumberLP(ps, res.newUsers);
16939                updateInstantAppInstallerLocked(pkgName);
16940            }
16941        }
16942    }
16943
16944    private void startIntentFilterVerifications(int userId, boolean replacing,
16945            PackageParser.Package pkg) {
16946        if (mIntentFilterVerifierComponent == null) {
16947            Slog.w(TAG, "No IntentFilter verification will not be done as "
16948                    + "there is no IntentFilterVerifier available!");
16949            return;
16950        }
16951
16952        final int verifierUid = getPackageUid(
16953                mIntentFilterVerifierComponent.getPackageName(),
16954                MATCH_DEBUG_TRIAGED_MISSING,
16955                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
16956
16957        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16958        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
16959        mHandler.sendMessage(msg);
16960
16961        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16962        for (int i = 0; i < childCount; i++) {
16963            PackageParser.Package childPkg = pkg.childPackages.get(i);
16964            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16965            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
16966            mHandler.sendMessage(msg);
16967        }
16968    }
16969
16970    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
16971            PackageParser.Package pkg) {
16972        int size = pkg.activities.size();
16973        if (size == 0) {
16974            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16975                    "No activity, so no need to verify any IntentFilter!");
16976            return;
16977        }
16978
16979        final boolean hasDomainURLs = hasDomainURLs(pkg);
16980        if (!hasDomainURLs) {
16981            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16982                    "No domain URLs, so no need to verify any IntentFilter!");
16983            return;
16984        }
16985
16986        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
16987                + " if any IntentFilter from the " + size
16988                + " Activities needs verification ...");
16989
16990        int count = 0;
16991        final String packageName = pkg.packageName;
16992
16993        synchronized (mPackages) {
16994            // If this is a new install and we see that we've already run verification for this
16995            // package, we have nothing to do: it means the state was restored from backup.
16996            if (!replacing) {
16997                IntentFilterVerificationInfo ivi =
16998                        mSettings.getIntentFilterVerificationLPr(packageName);
16999                if (ivi != null) {
17000                    if (DEBUG_DOMAIN_VERIFICATION) {
17001                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17002                                + ivi.getStatusString());
17003                    }
17004                    return;
17005                }
17006            }
17007
17008            // If any filters need to be verified, then all need to be.
17009            boolean needToVerify = false;
17010            for (PackageParser.Activity a : pkg.activities) {
17011                for (ActivityIntentInfo filter : a.intents) {
17012                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17013                        if (DEBUG_DOMAIN_VERIFICATION) {
17014                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
17015                        }
17016                        needToVerify = true;
17017                        break;
17018                    }
17019                }
17020            }
17021
17022            if (needToVerify) {
17023                final int verificationId = mIntentFilterVerificationToken++;
17024                for (PackageParser.Activity a : pkg.activities) {
17025                    for (ActivityIntentInfo filter : a.intents) {
17026                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17027                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17028                                    "Verification needed for IntentFilter:" + filter.toString());
17029                            mIntentFilterVerifier.addOneIntentFilterVerification(
17030                                    verifierUid, userId, verificationId, filter, packageName);
17031                            count++;
17032                        }
17033                    }
17034                }
17035            }
17036        }
17037
17038        if (count > 0) {
17039            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17040                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17041                    +  " for userId:" + userId);
17042            mIntentFilterVerifier.startVerifications(userId);
17043        } else {
17044            if (DEBUG_DOMAIN_VERIFICATION) {
17045                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17046            }
17047        }
17048    }
17049
17050    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17051        final ComponentName cn  = filter.activity.getComponentName();
17052        final String packageName = cn.getPackageName();
17053
17054        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17055                packageName);
17056        if (ivi == null) {
17057            return true;
17058        }
17059        int status = ivi.getStatus();
17060        switch (status) {
17061            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17062            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17063                return true;
17064
17065            default:
17066                // Nothing to do
17067                return false;
17068        }
17069    }
17070
17071    private static boolean isMultiArch(ApplicationInfo info) {
17072        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17073    }
17074
17075    private static boolean isExternal(PackageParser.Package pkg) {
17076        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17077    }
17078
17079    private static boolean isExternal(PackageSetting ps) {
17080        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17081    }
17082
17083    private static boolean isSystemApp(PackageParser.Package pkg) {
17084        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17085    }
17086
17087    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17088        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17089    }
17090
17091    private static boolean isOemApp(PackageParser.Package pkg) {
17092        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17093    }
17094
17095    private static boolean isVendorApp(PackageParser.Package pkg) {
17096        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
17097    }
17098
17099    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17100        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17101    }
17102
17103    private static boolean isSystemApp(PackageSetting ps) {
17104        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17105    }
17106
17107    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17108        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17109    }
17110
17111    private int packageFlagsToInstallFlags(PackageSetting ps) {
17112        int installFlags = 0;
17113        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17114            // This existing package was an external ASEC install when we have
17115            // the external flag without a UUID
17116            installFlags |= PackageManager.INSTALL_EXTERNAL;
17117        }
17118        if (ps.isForwardLocked()) {
17119            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17120        }
17121        return installFlags;
17122    }
17123
17124    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17125        if (isExternal(pkg)) {
17126            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17127                return mSettings.getExternalVersion();
17128            } else {
17129                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17130            }
17131        } else {
17132            return mSettings.getInternalVersion();
17133        }
17134    }
17135
17136    private void deleteTempPackageFiles() {
17137        final FilenameFilter filter = new FilenameFilter() {
17138            public boolean accept(File dir, String name) {
17139                return name.startsWith("vmdl") && name.endsWith(".tmp");
17140            }
17141        };
17142        for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) {
17143            file.delete();
17144        }
17145    }
17146
17147    @Override
17148    public void deletePackageAsUser(String packageName, int versionCode,
17149            IPackageDeleteObserver observer, int userId, int flags) {
17150        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17151                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17152    }
17153
17154    @Override
17155    public void deletePackageVersioned(VersionedPackage versionedPackage,
17156            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17157        final int callingUid = Binder.getCallingUid();
17158        mContext.enforceCallingOrSelfPermission(
17159                android.Manifest.permission.DELETE_PACKAGES, null);
17160        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
17161        Preconditions.checkNotNull(versionedPackage);
17162        Preconditions.checkNotNull(observer);
17163        Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(),
17164                PackageManager.VERSION_CODE_HIGHEST,
17165                Long.MAX_VALUE, "versionCode must be >= -1");
17166
17167        final String packageName = versionedPackage.getPackageName();
17168        final long versionCode = versionedPackage.getLongVersionCode();
17169        final String internalPackageName;
17170        synchronized (mPackages) {
17171            // Normalize package name to handle renamed packages and static libs
17172            internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode);
17173        }
17174
17175        final int uid = Binder.getCallingUid();
17176        if (!isOrphaned(internalPackageName)
17177                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17178            try {
17179                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17180                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17181                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17182                observer.onUserActionRequired(intent);
17183            } catch (RemoteException re) {
17184            }
17185            return;
17186        }
17187        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17188        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17189        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17190            mContext.enforceCallingOrSelfPermission(
17191                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17192                    "deletePackage for user " + userId);
17193        }
17194
17195        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17196            try {
17197                observer.onPackageDeleted(packageName,
17198                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17199            } catch (RemoteException re) {
17200            }
17201            return;
17202        }
17203
17204        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17205            try {
17206                observer.onPackageDeleted(packageName,
17207                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17208            } catch (RemoteException re) {
17209            }
17210            return;
17211        }
17212
17213        if (DEBUG_REMOVE) {
17214            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17215                    + " deleteAllUsers: " + deleteAllUsers + " version="
17216                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17217                    ? "VERSION_CODE_HIGHEST" : versionCode));
17218        }
17219        // Queue up an async operation since the package deletion may take a little while.
17220        mHandler.post(new Runnable() {
17221            public void run() {
17222                mHandler.removeCallbacks(this);
17223                int returnCode;
17224                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
17225                boolean doDeletePackage = true;
17226                if (ps != null) {
17227                    final boolean targetIsInstantApp =
17228                            ps.getInstantApp(UserHandle.getUserId(callingUid));
17229                    doDeletePackage = !targetIsInstantApp
17230                            || canViewInstantApps;
17231                }
17232                if (doDeletePackage) {
17233                    if (!deleteAllUsers) {
17234                        returnCode = deletePackageX(internalPackageName, versionCode,
17235                                userId, deleteFlags);
17236                    } else {
17237                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
17238                                internalPackageName, users);
17239                        // If nobody is blocking uninstall, proceed with delete for all users
17240                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17241                            returnCode = deletePackageX(internalPackageName, versionCode,
17242                                    userId, deleteFlags);
17243                        } else {
17244                            // Otherwise uninstall individually for users with blockUninstalls=false
17245                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17246                            for (int userId : users) {
17247                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17248                                    returnCode = deletePackageX(internalPackageName, versionCode,
17249                                            userId, userFlags);
17250                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17251                                        Slog.w(TAG, "Package delete failed for user " + userId
17252                                                + ", returnCode " + returnCode);
17253                                    }
17254                                }
17255                            }
17256                            // The app has only been marked uninstalled for certain users.
17257                            // We still need to report that delete was blocked
17258                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17259                        }
17260                    }
17261                } else {
17262                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17263                }
17264                try {
17265                    observer.onPackageDeleted(packageName, returnCode, null);
17266                } catch (RemoteException e) {
17267                    Log.i(TAG, "Observer no longer exists.");
17268                } //end catch
17269            } //end run
17270        });
17271    }
17272
17273    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17274        if (pkg.staticSharedLibName != null) {
17275            return pkg.manifestPackageName;
17276        }
17277        return pkg.packageName;
17278    }
17279
17280    private String resolveInternalPackageNameLPr(String packageName, long versionCode) {
17281        // Handle renamed packages
17282        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17283        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17284
17285        // Is this a static library?
17286        LongSparseArray<SharedLibraryEntry> versionedLib =
17287                mStaticLibsByDeclaringPackage.get(packageName);
17288        if (versionedLib == null || versionedLib.size() <= 0) {
17289            return packageName;
17290        }
17291
17292        // Figure out which lib versions the caller can see
17293        LongSparseLongArray versionsCallerCanSee = null;
17294        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17295        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17296                && callingAppId != Process.ROOT_UID) {
17297            versionsCallerCanSee = new LongSparseLongArray();
17298            String libName = versionedLib.valueAt(0).info.getName();
17299            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17300            if (uidPackages != null) {
17301                for (String uidPackage : uidPackages) {
17302                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17303                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17304                    if (libIdx >= 0) {
17305                        final long libVersion = ps.usesStaticLibrariesVersions[libIdx];
17306                        versionsCallerCanSee.append(libVersion, libVersion);
17307                    }
17308                }
17309            }
17310        }
17311
17312        // Caller can see nothing - done
17313        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17314            return packageName;
17315        }
17316
17317        // Find the version the caller can see and the app version code
17318        SharedLibraryEntry highestVersion = null;
17319        final int versionCount = versionedLib.size();
17320        for (int i = 0; i < versionCount; i++) {
17321            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17322            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17323                    libEntry.info.getLongVersion()) < 0) {
17324                continue;
17325            }
17326            final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode();
17327            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17328                if (libVersionCode == versionCode) {
17329                    return libEntry.apk;
17330                }
17331            } else if (highestVersion == null) {
17332                highestVersion = libEntry;
17333            } else if (libVersionCode  > highestVersion.info
17334                    .getDeclaringPackage().getLongVersionCode()) {
17335                highestVersion = libEntry;
17336            }
17337        }
17338
17339        if (highestVersion != null) {
17340            return highestVersion.apk;
17341        }
17342
17343        return packageName;
17344    }
17345
17346    boolean isCallerVerifier(int callingUid) {
17347        final int callingUserId = UserHandle.getUserId(callingUid);
17348        return mRequiredVerifierPackage != null &&
17349                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
17350    }
17351
17352    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17353        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17354              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17355            return true;
17356        }
17357        final int callingUserId = UserHandle.getUserId(callingUid);
17358        // If the caller installed the pkgName, then allow it to silently uninstall.
17359        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17360            return true;
17361        }
17362
17363        // Allow package verifier to silently uninstall.
17364        if (mRequiredVerifierPackage != null &&
17365                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17366            return true;
17367        }
17368
17369        // Allow package uninstaller to silently uninstall.
17370        if (mRequiredUninstallerPackage != null &&
17371                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17372            return true;
17373        }
17374
17375        // Allow storage manager to silently uninstall.
17376        if (mStorageManagerPackage != null &&
17377                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17378            return true;
17379        }
17380
17381        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
17382        // uninstall for device owner provisioning.
17383        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
17384                == PERMISSION_GRANTED) {
17385            return true;
17386        }
17387
17388        return false;
17389    }
17390
17391    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17392        int[] result = EMPTY_INT_ARRAY;
17393        for (int userId : userIds) {
17394            if (getBlockUninstallForUser(packageName, userId)) {
17395                result = ArrayUtils.appendInt(result, userId);
17396            }
17397        }
17398        return result;
17399    }
17400
17401    @Override
17402    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17403        final int callingUid = Binder.getCallingUid();
17404        if (getInstantAppPackageName(callingUid) != null
17405                && !isCallerSameApp(packageName, callingUid)) {
17406            return false;
17407        }
17408        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17409    }
17410
17411    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17412        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17413                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17414        try {
17415            if (dpm != null) {
17416                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17417                        /* callingUserOnly =*/ false);
17418                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17419                        : deviceOwnerComponentName.getPackageName();
17420                // Does the package contains the device owner?
17421                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17422                // this check is probably not needed, since DO should be registered as a device
17423                // admin on some user too. (Original bug for this: b/17657954)
17424                if (packageName.equals(deviceOwnerPackageName)) {
17425                    return true;
17426                }
17427                // Does it contain a device admin for any user?
17428                int[] users;
17429                if (userId == UserHandle.USER_ALL) {
17430                    users = sUserManager.getUserIds();
17431                } else {
17432                    users = new int[]{userId};
17433                }
17434                for (int i = 0; i < users.length; ++i) {
17435                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17436                        return true;
17437                    }
17438                }
17439            }
17440        } catch (RemoteException e) {
17441        }
17442        return false;
17443    }
17444
17445    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17446        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17447    }
17448
17449    /**
17450     *  This method is an internal method that could be get invoked either
17451     *  to delete an installed package or to clean up a failed installation.
17452     *  After deleting an installed package, a broadcast is sent to notify any
17453     *  listeners that the package has been removed. For cleaning up a failed
17454     *  installation, the broadcast is not necessary since the package's
17455     *  installation wouldn't have sent the initial broadcast either
17456     *  The key steps in deleting a package are
17457     *  deleting the package information in internal structures like mPackages,
17458     *  deleting the packages base directories through installd
17459     *  updating mSettings to reflect current status
17460     *  persisting settings for later use
17461     *  sending a broadcast if necessary
17462     */
17463    int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) {
17464        final PackageRemovedInfo info = new PackageRemovedInfo(this);
17465        final boolean res;
17466
17467        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17468                ? UserHandle.USER_ALL : userId;
17469
17470        if (isPackageDeviceAdmin(packageName, removeUser)) {
17471            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17472            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17473        }
17474
17475        PackageSetting uninstalledPs = null;
17476        PackageParser.Package pkg = null;
17477
17478        // for the uninstall-updates case and restricted profiles, remember the per-
17479        // user handle installed state
17480        int[] allUsers;
17481        synchronized (mPackages) {
17482            uninstalledPs = mSettings.mPackages.get(packageName);
17483            if (uninstalledPs == null) {
17484                Slog.w(TAG, "Not removing non-existent package " + packageName);
17485                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17486            }
17487
17488            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17489                    && uninstalledPs.versionCode != versionCode) {
17490                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17491                        + uninstalledPs.versionCode + " != " + versionCode);
17492                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17493            }
17494
17495            // Static shared libs can be declared by any package, so let us not
17496            // allow removing a package if it provides a lib others depend on.
17497            pkg = mPackages.get(packageName);
17498
17499            allUsers = sUserManager.getUserIds();
17500
17501            if (pkg != null && pkg.staticSharedLibName != null) {
17502                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17503                        pkg.staticSharedLibVersion);
17504                if (libEntry != null) {
17505                    for (int currUserId : allUsers) {
17506                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
17507                            continue;
17508                        }
17509                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17510                                libEntry.info, 0, currUserId);
17511                        if (!ArrayUtils.isEmpty(libClientPackages)) {
17512                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17513                                    + " hosting lib " + libEntry.info.getName() + " version "
17514                                    + libEntry.info.getLongVersion() + " used by " + libClientPackages
17515                                    + " for user " + currUserId);
17516                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17517                        }
17518                    }
17519                }
17520            }
17521
17522            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17523        }
17524
17525        final int freezeUser;
17526        if (isUpdatedSystemApp(uninstalledPs)
17527                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17528            // We're downgrading a system app, which will apply to all users, so
17529            // freeze them all during the downgrade
17530            freezeUser = UserHandle.USER_ALL;
17531        } else {
17532            freezeUser = removeUser;
17533        }
17534
17535        synchronized (mInstallLock) {
17536            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17537            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17538                    deleteFlags, "deletePackageX")) {
17539                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17540                        deleteFlags | PackageManager.DELETE_CHATTY, info, true, null);
17541            }
17542            synchronized (mPackages) {
17543                if (res) {
17544                    if (pkg != null) {
17545                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
17546                    }
17547                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
17548                    updateInstantAppInstallerLocked(packageName);
17549                }
17550            }
17551        }
17552
17553        if (res) {
17554            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17555            info.sendPackageRemovedBroadcasts(killApp);
17556            info.sendSystemPackageUpdatedBroadcasts();
17557            info.sendSystemPackageAppearedBroadcasts();
17558        }
17559        // Force a gc here.
17560        Runtime.getRuntime().gc();
17561        // Delete the resources here after sending the broadcast to let
17562        // other processes clean up before deleting resources.
17563        if (info.args != null) {
17564            synchronized (mInstallLock) {
17565                info.args.doPostDeleteLI(true);
17566            }
17567        }
17568
17569        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17570    }
17571
17572    static class PackageRemovedInfo {
17573        final PackageSender packageSender;
17574        String removedPackage;
17575        String installerPackageName;
17576        int uid = -1;
17577        int removedAppId = -1;
17578        int[] origUsers;
17579        int[] removedUsers = null;
17580        int[] broadcastUsers = null;
17581        int[] instantUserIds = null;
17582        SparseArray<Integer> installReasons;
17583        boolean isRemovedPackageSystemUpdate = false;
17584        boolean isUpdate;
17585        boolean dataRemoved;
17586        boolean removedForAllUsers;
17587        boolean isStaticSharedLib;
17588        // Clean up resources deleted packages.
17589        InstallArgs args = null;
17590        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17591        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17592
17593        PackageRemovedInfo(PackageSender packageSender) {
17594            this.packageSender = packageSender;
17595        }
17596
17597        void sendPackageRemovedBroadcasts(boolean killApp) {
17598            sendPackageRemovedBroadcastInternal(killApp);
17599            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17600            for (int i = 0; i < childCount; i++) {
17601                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17602                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17603            }
17604        }
17605
17606        void sendSystemPackageUpdatedBroadcasts() {
17607            if (isRemovedPackageSystemUpdate) {
17608                sendSystemPackageUpdatedBroadcastsInternal();
17609                final int childCount = (removedChildPackages != null)
17610                        ? removedChildPackages.size() : 0;
17611                for (int i = 0; i < childCount; i++) {
17612                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17613                    if (childInfo.isRemovedPackageSystemUpdate) {
17614                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17615                    }
17616                }
17617            }
17618        }
17619
17620        void sendSystemPackageAppearedBroadcasts() {
17621            final int packageCount = (appearedChildPackages != null)
17622                    ? appearedChildPackages.size() : 0;
17623            for (int i = 0; i < packageCount; i++) {
17624                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17625                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
17626                    true /*sendBootCompleted*/, false /*startReceiver*/,
17627                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null);
17628            }
17629        }
17630
17631        private void sendSystemPackageUpdatedBroadcastsInternal() {
17632            Bundle extras = new Bundle(2);
17633            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17634            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17635            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
17636                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
17637            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
17638                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
17639            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
17640                null, null, 0, removedPackage, null, null, null);
17641            if (installerPackageName != null) {
17642                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
17643                        removedPackage, extras, 0 /*flags*/,
17644                        installerPackageName, null, null, null);
17645                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
17646                        removedPackage, extras, 0 /*flags*/,
17647                        installerPackageName, null, null, null);
17648            }
17649        }
17650
17651        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17652            // Don't send static shared library removal broadcasts as these
17653            // libs are visible only the the apps that depend on them an one
17654            // cannot remove the library if it has a dependency.
17655            if (isStaticSharedLib) {
17656                return;
17657            }
17658            Bundle extras = new Bundle(2);
17659            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17660            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17661            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17662            if (isUpdate || isRemovedPackageSystemUpdate) {
17663                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17664            }
17665            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17666            if (removedPackage != null) {
17667                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
17668                    removedPackage, extras, 0, null /*targetPackage*/, null,
17669                    broadcastUsers, instantUserIds);
17670                if (installerPackageName != null) {
17671                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
17672                            removedPackage, extras, 0 /*flags*/,
17673                            installerPackageName, null, broadcastUsers, instantUserIds);
17674                }
17675                if (dataRemoved && !isRemovedPackageSystemUpdate) {
17676                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
17677                        removedPackage, extras,
17678                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17679                        null, null, broadcastUsers, instantUserIds);
17680                    packageSender.notifyPackageRemoved(removedPackage);
17681                }
17682            }
17683            if (removedAppId >= 0) {
17684                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
17685                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17686                    null, null, broadcastUsers, instantUserIds);
17687            }
17688        }
17689
17690        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
17691            removedUsers = userIds;
17692            if (removedUsers == null) {
17693                broadcastUsers = null;
17694                return;
17695            }
17696
17697            broadcastUsers = EMPTY_INT_ARRAY;
17698            instantUserIds = EMPTY_INT_ARRAY;
17699            for (int i = userIds.length - 1; i >= 0; --i) {
17700                final int userId = userIds[i];
17701                if (deletedPackageSetting.getInstantApp(userId)) {
17702                    instantUserIds = ArrayUtils.appendInt(instantUserIds, userId);
17703                } else {
17704                    broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
17705                }
17706            }
17707        }
17708    }
17709
17710    /*
17711     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
17712     * flag is not set, the data directory is removed as well.
17713     * make sure this flag is set for partially installed apps. If not its meaningless to
17714     * delete a partially installed application.
17715     */
17716    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
17717            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
17718        String packageName = ps.name;
17719        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
17720        // Retrieve object to delete permissions for shared user later on
17721        final PackageParser.Package deletedPkg;
17722        final PackageSetting deletedPs;
17723        // reader
17724        synchronized (mPackages) {
17725            deletedPkg = mPackages.get(packageName);
17726            deletedPs = mSettings.mPackages.get(packageName);
17727            if (outInfo != null) {
17728                outInfo.removedPackage = packageName;
17729                outInfo.installerPackageName = ps.installerPackageName;
17730                outInfo.isStaticSharedLib = deletedPkg != null
17731                        && deletedPkg.staticSharedLibName != null;
17732                outInfo.populateUsers(deletedPs == null ? null
17733                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
17734            }
17735        }
17736
17737        removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0);
17738
17739        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
17740            final PackageParser.Package resolvedPkg;
17741            if (deletedPkg != null) {
17742                resolvedPkg = deletedPkg;
17743            } else {
17744                // We don't have a parsed package when it lives on an ejected
17745                // adopted storage device, so fake something together
17746                resolvedPkg = new PackageParser.Package(ps.name);
17747                resolvedPkg.setVolumeUuid(ps.volumeUuid);
17748            }
17749            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
17750                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17751            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
17752            if (outInfo != null) {
17753                outInfo.dataRemoved = true;
17754            }
17755            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
17756        }
17757
17758        int removedAppId = -1;
17759
17760        // writer
17761        synchronized (mPackages) {
17762            boolean installedStateChanged = false;
17763            if (deletedPs != null) {
17764                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
17765                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
17766                    clearDefaultBrowserIfNeeded(packageName);
17767                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
17768                    removedAppId = mSettings.removePackageLPw(packageName);
17769                    if (outInfo != null) {
17770                        outInfo.removedAppId = removedAppId;
17771                    }
17772                    mPermissionManager.updatePermissions(
17773                            deletedPs.name, null, false, mPackages.values(), mPermissionCallback);
17774                    if (deletedPs.sharedUser != null) {
17775                        // Remove permissions associated with package. Since runtime
17776                        // permissions are per user we have to kill the removed package
17777                        // or packages running under the shared user of the removed
17778                        // package if revoking the permissions requested only by the removed
17779                        // package is successful and this causes a change in gids.
17780                        for (int userId : UserManagerService.getInstance().getUserIds()) {
17781                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
17782                                    userId);
17783                            if (userIdToKill == UserHandle.USER_ALL
17784                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
17785                                // If gids changed for this user, kill all affected packages.
17786                                mHandler.post(new Runnable() {
17787                                    @Override
17788                                    public void run() {
17789                                        // This has to happen with no lock held.
17790                                        killApplication(deletedPs.name, deletedPs.appId,
17791                                                KILL_APP_REASON_GIDS_CHANGED);
17792                                    }
17793                                });
17794                                break;
17795                            }
17796                        }
17797                    }
17798                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
17799                }
17800                // make sure to preserve per-user disabled state if this removal was just
17801                // a downgrade of a system app to the factory package
17802                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
17803                    if (DEBUG_REMOVE) {
17804                        Slog.d(TAG, "Propagating install state across downgrade");
17805                    }
17806                    for (int userId : allUserHandles) {
17807                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17808                        if (DEBUG_REMOVE) {
17809                            Slog.d(TAG, "    user " + userId + " => " + installed);
17810                        }
17811                        if (installed != ps.getInstalled(userId)) {
17812                            installedStateChanged = true;
17813                        }
17814                        ps.setInstalled(installed, userId);
17815                    }
17816                }
17817            }
17818            // can downgrade to reader
17819            if (writeSettings) {
17820                // Save settings now
17821                mSettings.writeLPr();
17822            }
17823            if (installedStateChanged) {
17824                mSettings.writeKernelMappingLPr(ps);
17825            }
17826        }
17827        if (removedAppId != -1) {
17828            // A user ID was deleted here. Go through all users and remove it
17829            // from KeyStore.
17830            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
17831        }
17832    }
17833
17834    static boolean locationIsPrivileged(String path) {
17835        try {
17836            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
17837            final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
17838            return path.startsWith(privilegedAppDir.getCanonicalPath())
17839                    || path.startsWith(privilegedVendorAppDir.getCanonicalPath());
17840        } catch (IOException e) {
17841            Slog.e(TAG, "Unable to access code path " + path);
17842        }
17843        return false;
17844    }
17845
17846    static boolean locationIsOem(String path) {
17847        try {
17848            return path.startsWith(Environment.getOemDirectory().getCanonicalPath());
17849        } catch (IOException e) {
17850            Slog.e(TAG, "Unable to access code path " + path);
17851        }
17852        return false;
17853    }
17854
17855    static boolean locationIsVendor(String path) {
17856        try {
17857            return path.startsWith(Environment.getVendorDirectory().getCanonicalPath());
17858        } catch (IOException e) {
17859            Slog.e(TAG, "Unable to access code path " + path);
17860        }
17861        return false;
17862    }
17863
17864    /*
17865     * Tries to delete system package.
17866     */
17867    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
17868            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
17869            boolean writeSettings) {
17870        if (deletedPs.parentPackageName != null) {
17871            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
17872            return false;
17873        }
17874
17875        final boolean applyUserRestrictions
17876                = (allUserHandles != null) && (outInfo.origUsers != null);
17877        final PackageSetting disabledPs;
17878        // Confirm if the system package has been updated
17879        // An updated system app can be deleted. This will also have to restore
17880        // the system pkg from system partition
17881        // reader
17882        synchronized (mPackages) {
17883            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
17884        }
17885
17886        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
17887                + " disabledPs=" + disabledPs);
17888
17889        if (disabledPs == null) {
17890            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
17891            return false;
17892        } else if (DEBUG_REMOVE) {
17893            Slog.d(TAG, "Deleting system pkg from data partition");
17894        }
17895
17896        if (DEBUG_REMOVE) {
17897            if (applyUserRestrictions) {
17898                Slog.d(TAG, "Remembering install states:");
17899                for (int userId : allUserHandles) {
17900                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
17901                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
17902                }
17903            }
17904        }
17905
17906        // Delete the updated package
17907        outInfo.isRemovedPackageSystemUpdate = true;
17908        if (outInfo.removedChildPackages != null) {
17909            final int childCount = (deletedPs.childPackageNames != null)
17910                    ? deletedPs.childPackageNames.size() : 0;
17911            for (int i = 0; i < childCount; i++) {
17912                String childPackageName = deletedPs.childPackageNames.get(i);
17913                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
17914                        .contains(childPackageName)) {
17915                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17916                            childPackageName);
17917                    if (childInfo != null) {
17918                        childInfo.isRemovedPackageSystemUpdate = true;
17919                    }
17920                }
17921            }
17922        }
17923
17924        if (disabledPs.versionCode < deletedPs.versionCode) {
17925            // Delete data for downgrades
17926            flags &= ~PackageManager.DELETE_KEEP_DATA;
17927        } else {
17928            // Preserve data by setting flag
17929            flags |= PackageManager.DELETE_KEEP_DATA;
17930        }
17931
17932        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
17933                outInfo, writeSettings, disabledPs.pkg);
17934        if (!ret) {
17935            return false;
17936        }
17937
17938        // writer
17939        synchronized (mPackages) {
17940            // NOTE: The system package always needs to be enabled; even if it's for
17941            // a compressed stub. If we don't, installing the system package fails
17942            // during scan [scanning checks the disabled packages]. We will reverse
17943            // this later, after we've "installed" the stub.
17944            // Reinstate the old system package
17945            enableSystemPackageLPw(disabledPs.pkg);
17946            // Remove any native libraries from the upgraded package.
17947            removeNativeBinariesLI(deletedPs);
17948        }
17949
17950        // Install the system package
17951        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
17952        try {
17953            installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles,
17954                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
17955        } catch (PackageManagerException e) {
17956            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
17957                    + e.getMessage());
17958            return false;
17959        } finally {
17960            if (disabledPs.pkg.isStub) {
17961                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
17962            }
17963        }
17964        return true;
17965    }
17966
17967    /**
17968     * Installs a package that's already on the system partition.
17969     */
17970    private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString,
17971            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
17972            @Nullable PermissionsState origPermissionState, boolean writeSettings)
17973                    throws PackageManagerException {
17974        @ParseFlags int parseFlags =
17975                mDefParseFlags
17976                | PackageParser.PARSE_MUST_BE_APK
17977                | PackageParser.PARSE_IS_SYSTEM_DIR;
17978        @ScanFlags int scanFlags = SCAN_AS_SYSTEM;
17979        if (isPrivileged || locationIsPrivileged(codePathString)) {
17980            scanFlags |= SCAN_AS_PRIVILEGED;
17981        }
17982        if (locationIsOem(codePathString)) {
17983            scanFlags |= SCAN_AS_OEM;
17984        }
17985        if (locationIsVendor(codePathString)) {
17986            scanFlags |= SCAN_AS_VENDOR;
17987        }
17988
17989        final File codePath = new File(codePathString);
17990        final PackageParser.Package pkg =
17991                scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null);
17992
17993        try {
17994            // update shared libraries for the newly re-installed system package
17995            updateSharedLibrariesLPr(pkg, null);
17996        } catch (PackageManagerException e) {
17997            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17998        }
17999
18000        prepareAppDataAfterInstallLIF(pkg);
18001
18002        // writer
18003        synchronized (mPackages) {
18004            PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
18005
18006            // Propagate the permissions state as we do not want to drop on the floor
18007            // runtime permissions. The update permissions method below will take
18008            // care of removing obsolete permissions and grant install permissions.
18009            if (origPermissionState != null) {
18010                ps.getPermissionsState().copyFrom(origPermissionState);
18011            }
18012            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
18013                    mPermissionCallback);
18014
18015            final boolean applyUserRestrictions
18016                    = (allUserHandles != null) && (origUserHandles != null);
18017            if (applyUserRestrictions) {
18018                boolean installedStateChanged = false;
18019                if (DEBUG_REMOVE) {
18020                    Slog.d(TAG, "Propagating install state across reinstall");
18021                }
18022                for (int userId : allUserHandles) {
18023                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
18024                    if (DEBUG_REMOVE) {
18025                        Slog.d(TAG, "    user " + userId + " => " + installed);
18026                    }
18027                    if (installed != ps.getInstalled(userId)) {
18028                        installedStateChanged = true;
18029                    }
18030                    ps.setInstalled(installed, userId);
18031
18032                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18033                }
18034                // Regardless of writeSettings we need to ensure that this restriction
18035                // state propagation is persisted
18036                mSettings.writeAllUsersPackageRestrictionsLPr();
18037                if (installedStateChanged) {
18038                    mSettings.writeKernelMappingLPr(ps);
18039                }
18040            }
18041            // can downgrade to reader here
18042            if (writeSettings) {
18043                mSettings.writeLPr();
18044            }
18045        }
18046        return pkg;
18047    }
18048
18049    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18050            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18051            PackageRemovedInfo outInfo, boolean writeSettings,
18052            PackageParser.Package replacingPackage) {
18053        synchronized (mPackages) {
18054            if (outInfo != null) {
18055                outInfo.uid = ps.appId;
18056            }
18057
18058            if (outInfo != null && outInfo.removedChildPackages != null) {
18059                final int childCount = (ps.childPackageNames != null)
18060                        ? ps.childPackageNames.size() : 0;
18061                for (int i = 0; i < childCount; i++) {
18062                    String childPackageName = ps.childPackageNames.get(i);
18063                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18064                    if (childPs == null) {
18065                        return false;
18066                    }
18067                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18068                            childPackageName);
18069                    if (childInfo != null) {
18070                        childInfo.uid = childPs.appId;
18071                    }
18072                }
18073            }
18074        }
18075
18076        // Delete package data from internal structures and also remove data if flag is set
18077        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18078
18079        // Delete the child packages data
18080        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18081        for (int i = 0; i < childCount; i++) {
18082            PackageSetting childPs;
18083            synchronized (mPackages) {
18084                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18085            }
18086            if (childPs != null) {
18087                PackageRemovedInfo childOutInfo = (outInfo != null
18088                        && outInfo.removedChildPackages != null)
18089                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18090                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18091                        && (replacingPackage != null
18092                        && !replacingPackage.hasChildPackage(childPs.name))
18093                        ? flags & ~DELETE_KEEP_DATA : flags;
18094                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18095                        deleteFlags, writeSettings);
18096            }
18097        }
18098
18099        // Delete application code and resources only for parent packages
18100        if (ps.parentPackageName == null) {
18101            if (deleteCodeAndResources && (outInfo != null)) {
18102                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18103                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18104                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18105            }
18106        }
18107
18108        return true;
18109    }
18110
18111    @Override
18112    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18113            int userId) {
18114        mContext.enforceCallingOrSelfPermission(
18115                android.Manifest.permission.DELETE_PACKAGES, null);
18116        synchronized (mPackages) {
18117            // Cannot block uninstall of static shared libs as they are
18118            // considered a part of the using app (emulating static linking).
18119            // Also static libs are installed always on internal storage.
18120            PackageParser.Package pkg = mPackages.get(packageName);
18121            if (pkg != null && pkg.staticSharedLibName != null) {
18122                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18123                        + " providing static shared library: " + pkg.staticSharedLibName);
18124                return false;
18125            }
18126            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18127            mSettings.writePackageRestrictionsLPr(userId);
18128        }
18129        return true;
18130    }
18131
18132    @Override
18133    public boolean getBlockUninstallForUser(String packageName, int userId) {
18134        synchronized (mPackages) {
18135            final PackageSetting ps = mSettings.mPackages.get(packageName);
18136            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
18137                return false;
18138            }
18139            return mSettings.getBlockUninstallLPr(userId, packageName);
18140        }
18141    }
18142
18143    @Override
18144    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18145        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
18146        synchronized (mPackages) {
18147            PackageSetting ps = mSettings.mPackages.get(packageName);
18148            if (ps == null) {
18149                Log.w(TAG, "Package doesn't exist: " + packageName);
18150                return false;
18151            }
18152            if (systemUserApp) {
18153                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18154            } else {
18155                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18156            }
18157            mSettings.writeLPr();
18158        }
18159        return true;
18160    }
18161
18162    /*
18163     * This method handles package deletion in general
18164     */
18165    private boolean deletePackageLIF(String packageName, UserHandle user,
18166            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18167            PackageRemovedInfo outInfo, boolean writeSettings,
18168            PackageParser.Package replacingPackage) {
18169        if (packageName == null) {
18170            Slog.w(TAG, "Attempt to delete null packageName.");
18171            return false;
18172        }
18173
18174        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18175
18176        PackageSetting ps;
18177        synchronized (mPackages) {
18178            ps = mSettings.mPackages.get(packageName);
18179            if (ps == null) {
18180                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18181                return false;
18182            }
18183
18184            if (ps.parentPackageName != null && (!isSystemApp(ps)
18185                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18186                if (DEBUG_REMOVE) {
18187                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18188                            + ((user == null) ? UserHandle.USER_ALL : user));
18189                }
18190                final int removedUserId = (user != null) ? user.getIdentifier()
18191                        : UserHandle.USER_ALL;
18192                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18193                    return false;
18194                }
18195                markPackageUninstalledForUserLPw(ps, user);
18196                scheduleWritePackageRestrictionsLocked(user);
18197                return true;
18198            }
18199        }
18200
18201        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18202                && user.getIdentifier() != UserHandle.USER_ALL)) {
18203            // The caller is asking that the package only be deleted for a single
18204            // user.  To do this, we just mark its uninstalled state and delete
18205            // its data. If this is a system app, we only allow this to happen if
18206            // they have set the special DELETE_SYSTEM_APP which requests different
18207            // semantics than normal for uninstalling system apps.
18208            markPackageUninstalledForUserLPw(ps, user);
18209
18210            if (!isSystemApp(ps)) {
18211                // Do not uninstall the APK if an app should be cached
18212                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18213                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18214                    // Other user still have this package installed, so all
18215                    // we need to do is clear this user's data and save that
18216                    // it is uninstalled.
18217                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18218                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18219                        return false;
18220                    }
18221                    scheduleWritePackageRestrictionsLocked(user);
18222                    return true;
18223                } else {
18224                    // We need to set it back to 'installed' so the uninstall
18225                    // broadcasts will be sent correctly.
18226                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18227                    ps.setInstalled(true, user.getIdentifier());
18228                    mSettings.writeKernelMappingLPr(ps);
18229                }
18230            } else {
18231                // This is a system app, so we assume that the
18232                // other users still have this package installed, so all
18233                // we need to do is clear this user's data and save that
18234                // it is uninstalled.
18235                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18236                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18237                    return false;
18238                }
18239                scheduleWritePackageRestrictionsLocked(user);
18240                return true;
18241            }
18242        }
18243
18244        // If we are deleting a composite package for all users, keep track
18245        // of result for each child.
18246        if (ps.childPackageNames != null && outInfo != null) {
18247            synchronized (mPackages) {
18248                final int childCount = ps.childPackageNames.size();
18249                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18250                for (int i = 0; i < childCount; i++) {
18251                    String childPackageName = ps.childPackageNames.get(i);
18252                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18253                    childInfo.removedPackage = childPackageName;
18254                    childInfo.installerPackageName = ps.installerPackageName;
18255                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18256                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18257                    if (childPs != null) {
18258                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18259                    }
18260                }
18261            }
18262        }
18263
18264        boolean ret = false;
18265        if (isSystemApp(ps)) {
18266            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18267            // When an updated system application is deleted we delete the existing resources
18268            // as well and fall back to existing code in system partition
18269            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18270        } else {
18271            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18272            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18273                    outInfo, writeSettings, replacingPackage);
18274        }
18275
18276        // Take a note whether we deleted the package for all users
18277        if (outInfo != null) {
18278            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18279            if (outInfo.removedChildPackages != null) {
18280                synchronized (mPackages) {
18281                    final int childCount = outInfo.removedChildPackages.size();
18282                    for (int i = 0; i < childCount; i++) {
18283                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18284                        if (childInfo != null) {
18285                            childInfo.removedForAllUsers = mPackages.get(
18286                                    childInfo.removedPackage) == null;
18287                        }
18288                    }
18289                }
18290            }
18291            // If we uninstalled an update to a system app there may be some
18292            // child packages that appeared as they are declared in the system
18293            // app but were not declared in the update.
18294            if (isSystemApp(ps)) {
18295                synchronized (mPackages) {
18296                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18297                    final int childCount = (updatedPs.childPackageNames != null)
18298                            ? updatedPs.childPackageNames.size() : 0;
18299                    for (int i = 0; i < childCount; i++) {
18300                        String childPackageName = updatedPs.childPackageNames.get(i);
18301                        if (outInfo.removedChildPackages == null
18302                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18303                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18304                            if (childPs == null) {
18305                                continue;
18306                            }
18307                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18308                            installRes.name = childPackageName;
18309                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18310                            installRes.pkg = mPackages.get(childPackageName);
18311                            installRes.uid = childPs.pkg.applicationInfo.uid;
18312                            if (outInfo.appearedChildPackages == null) {
18313                                outInfo.appearedChildPackages = new ArrayMap<>();
18314                            }
18315                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18316                        }
18317                    }
18318                }
18319            }
18320        }
18321
18322        return ret;
18323    }
18324
18325    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18326        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18327                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18328        for (int nextUserId : userIds) {
18329            if (DEBUG_REMOVE) {
18330                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18331            }
18332            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18333                    false /*installed*/,
18334                    true /*stopped*/,
18335                    true /*notLaunched*/,
18336                    false /*hidden*/,
18337                    false /*suspended*/,
18338                    false /*instantApp*/,
18339                    false /*virtualPreload*/,
18340                    null /*lastDisableAppCaller*/,
18341                    null /*enabledComponents*/,
18342                    null /*disabledComponents*/,
18343                    ps.readUserState(nextUserId).domainVerificationStatus,
18344                    0, PackageManager.INSTALL_REASON_UNKNOWN);
18345        }
18346        mSettings.writeKernelMappingLPr(ps);
18347    }
18348
18349    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18350            PackageRemovedInfo outInfo) {
18351        final PackageParser.Package pkg;
18352        synchronized (mPackages) {
18353            pkg = mPackages.get(ps.name);
18354        }
18355
18356        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18357                : new int[] {userId};
18358        for (int nextUserId : userIds) {
18359            if (DEBUG_REMOVE) {
18360                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18361                        + nextUserId);
18362            }
18363
18364            destroyAppDataLIF(pkg, userId,
18365                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18366            destroyAppProfilesLIF(pkg, userId);
18367            clearDefaultBrowserIfNeededForUser(ps.name, userId);
18368            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18369            schedulePackageCleaning(ps.name, nextUserId, false);
18370            synchronized (mPackages) {
18371                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18372                    scheduleWritePackageRestrictionsLocked(nextUserId);
18373                }
18374                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18375            }
18376        }
18377
18378        if (outInfo != null) {
18379            outInfo.removedPackage = ps.name;
18380            outInfo.installerPackageName = ps.installerPackageName;
18381            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18382            outInfo.removedAppId = ps.appId;
18383            outInfo.removedUsers = userIds;
18384            outInfo.broadcastUsers = userIds;
18385        }
18386
18387        return true;
18388    }
18389
18390    private final class ClearStorageConnection implements ServiceConnection {
18391        IMediaContainerService mContainerService;
18392
18393        @Override
18394        public void onServiceConnected(ComponentName name, IBinder service) {
18395            synchronized (this) {
18396                mContainerService = IMediaContainerService.Stub
18397                        .asInterface(Binder.allowBlocking(service));
18398                notifyAll();
18399            }
18400        }
18401
18402        @Override
18403        public void onServiceDisconnected(ComponentName name) {
18404        }
18405    }
18406
18407    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18408        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18409
18410        final boolean mounted;
18411        if (Environment.isExternalStorageEmulated()) {
18412            mounted = true;
18413        } else {
18414            final String status = Environment.getExternalStorageState();
18415
18416            mounted = status.equals(Environment.MEDIA_MOUNTED)
18417                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18418        }
18419
18420        if (!mounted) {
18421            return;
18422        }
18423
18424        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18425        int[] users;
18426        if (userId == UserHandle.USER_ALL) {
18427            users = sUserManager.getUserIds();
18428        } else {
18429            users = new int[] { userId };
18430        }
18431        final ClearStorageConnection conn = new ClearStorageConnection();
18432        if (mContext.bindServiceAsUser(
18433                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18434            try {
18435                for (int curUser : users) {
18436                    long timeout = SystemClock.uptimeMillis() + 5000;
18437                    synchronized (conn) {
18438                        long now;
18439                        while (conn.mContainerService == null &&
18440                                (now = SystemClock.uptimeMillis()) < timeout) {
18441                            try {
18442                                conn.wait(timeout - now);
18443                            } catch (InterruptedException e) {
18444                            }
18445                        }
18446                    }
18447                    if (conn.mContainerService == null) {
18448                        return;
18449                    }
18450
18451                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18452                    clearDirectory(conn.mContainerService,
18453                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18454                    if (allData) {
18455                        clearDirectory(conn.mContainerService,
18456                                userEnv.buildExternalStorageAppDataDirs(packageName));
18457                        clearDirectory(conn.mContainerService,
18458                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18459                    }
18460                }
18461            } finally {
18462                mContext.unbindService(conn);
18463            }
18464        }
18465    }
18466
18467    @Override
18468    public void clearApplicationProfileData(String packageName) {
18469        enforceSystemOrRoot("Only the system can clear all profile data");
18470
18471        final PackageParser.Package pkg;
18472        synchronized (mPackages) {
18473            pkg = mPackages.get(packageName);
18474        }
18475
18476        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18477            synchronized (mInstallLock) {
18478                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18479            }
18480        }
18481    }
18482
18483    @Override
18484    public void clearApplicationUserData(final String packageName,
18485            final IPackageDataObserver observer, final int userId) {
18486        mContext.enforceCallingOrSelfPermission(
18487                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18488
18489        final int callingUid = Binder.getCallingUid();
18490        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18491                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18492
18493        final PackageSetting ps = mSettings.getPackageLPr(packageName);
18494        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
18495        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18496            throw new SecurityException("Cannot clear data for a protected package: "
18497                    + packageName);
18498        }
18499        // Queue up an async operation since the package deletion may take a little while.
18500        mHandler.post(new Runnable() {
18501            public void run() {
18502                mHandler.removeCallbacks(this);
18503                final boolean succeeded;
18504                if (!filterApp) {
18505                    try (PackageFreezer freezer = freezePackage(packageName,
18506                            "clearApplicationUserData")) {
18507                        synchronized (mInstallLock) {
18508                            succeeded = clearApplicationUserDataLIF(packageName, userId);
18509                        }
18510                        clearExternalStorageDataSync(packageName, userId, true);
18511                        synchronized (mPackages) {
18512                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18513                                    packageName, userId);
18514                        }
18515                    }
18516                    if (succeeded) {
18517                        // invoke DeviceStorageMonitor's update method to clear any notifications
18518                        DeviceStorageMonitorInternal dsm = LocalServices
18519                                .getService(DeviceStorageMonitorInternal.class);
18520                        if (dsm != null) {
18521                            dsm.checkMemory();
18522                        }
18523                    }
18524                } else {
18525                    succeeded = false;
18526                }
18527                if (observer != null) {
18528                    try {
18529                        observer.onRemoveCompleted(packageName, succeeded);
18530                    } catch (RemoteException e) {
18531                        Log.i(TAG, "Observer no longer exists.");
18532                    }
18533                } //end if observer
18534            } //end run
18535        });
18536    }
18537
18538    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18539        if (packageName == null) {
18540            Slog.w(TAG, "Attempt to delete null packageName.");
18541            return false;
18542        }
18543
18544        // Try finding details about the requested package
18545        PackageParser.Package pkg;
18546        synchronized (mPackages) {
18547            pkg = mPackages.get(packageName);
18548            if (pkg == null) {
18549                final PackageSetting ps = mSettings.mPackages.get(packageName);
18550                if (ps != null) {
18551                    pkg = ps.pkg;
18552                }
18553            }
18554
18555            if (pkg == null) {
18556                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18557                return false;
18558            }
18559
18560            PackageSetting ps = (PackageSetting) pkg.mExtras;
18561            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18562        }
18563
18564        clearAppDataLIF(pkg, userId,
18565                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18566
18567        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18568        removeKeystoreDataIfNeeded(userId, appId);
18569
18570        UserManagerInternal umInternal = getUserManagerInternal();
18571        final int flags;
18572        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18573            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18574        } else if (umInternal.isUserRunning(userId)) {
18575            flags = StorageManager.FLAG_STORAGE_DE;
18576        } else {
18577            flags = 0;
18578        }
18579        prepareAppDataContentsLIF(pkg, userId, flags);
18580
18581        return true;
18582    }
18583
18584    /**
18585     * Reverts user permission state changes (permissions and flags) in
18586     * all packages for a given user.
18587     *
18588     * @param userId The device user for which to do a reset.
18589     */
18590    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18591        final int packageCount = mPackages.size();
18592        for (int i = 0; i < packageCount; i++) {
18593            PackageParser.Package pkg = mPackages.valueAt(i);
18594            PackageSetting ps = (PackageSetting) pkg.mExtras;
18595            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18596        }
18597    }
18598
18599    private void resetNetworkPolicies(int userId) {
18600        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18601    }
18602
18603    /**
18604     * Reverts user permission state changes (permissions and flags).
18605     *
18606     * @param ps The package for which to reset.
18607     * @param userId The device user for which to do a reset.
18608     */
18609    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18610            final PackageSetting ps, final int userId) {
18611        if (ps.pkg == null) {
18612            return;
18613        }
18614
18615        // These are flags that can change base on user actions.
18616        final int userSettableMask = FLAG_PERMISSION_USER_SET
18617                | FLAG_PERMISSION_USER_FIXED
18618                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18619                | FLAG_PERMISSION_REVIEW_REQUIRED;
18620
18621        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18622                | FLAG_PERMISSION_POLICY_FIXED;
18623
18624        boolean writeInstallPermissions = false;
18625        boolean writeRuntimePermissions = false;
18626
18627        final int permissionCount = ps.pkg.requestedPermissions.size();
18628        for (int i = 0; i < permissionCount; i++) {
18629            final String permName = ps.pkg.requestedPermissions.get(i);
18630            final BasePermission bp =
18631                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
18632            if (bp == null) {
18633                continue;
18634            }
18635
18636            // If shared user we just reset the state to which only this app contributed.
18637            if (ps.sharedUser != null) {
18638                boolean used = false;
18639                final int packageCount = ps.sharedUser.packages.size();
18640                for (int j = 0; j < packageCount; j++) {
18641                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18642                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18643                            && pkg.pkg.requestedPermissions.contains(permName)) {
18644                        used = true;
18645                        break;
18646                    }
18647                }
18648                if (used) {
18649                    continue;
18650                }
18651            }
18652
18653            final PermissionsState permissionsState = ps.getPermissionsState();
18654
18655            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
18656
18657            // Always clear the user settable flags.
18658            final boolean hasInstallState =
18659                    permissionsState.getInstallPermissionState(permName) != null;
18660            // If permission review is enabled and this is a legacy app, mark the
18661            // permission as requiring a review as this is the initial state.
18662            int flags = 0;
18663            if (mSettings.mPermissions.mPermissionReviewRequired
18664                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
18665                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
18666            }
18667            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
18668                if (hasInstallState) {
18669                    writeInstallPermissions = true;
18670                } else {
18671                    writeRuntimePermissions = true;
18672                }
18673            }
18674
18675            // Below is only runtime permission handling.
18676            if (!bp.isRuntime()) {
18677                continue;
18678            }
18679
18680            // Never clobber system or policy.
18681            if ((oldFlags & policyOrSystemFlags) != 0) {
18682                continue;
18683            }
18684
18685            // If this permission was granted by default, make sure it is.
18686            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
18687                if (permissionsState.grantRuntimePermission(bp, userId)
18688                        != PERMISSION_OPERATION_FAILURE) {
18689                    writeRuntimePermissions = true;
18690                }
18691            // If permission review is enabled the permissions for a legacy apps
18692            // are represented as constantly granted runtime ones, so don't revoke.
18693            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
18694                // Otherwise, reset the permission.
18695                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
18696                switch (revokeResult) {
18697                    case PERMISSION_OPERATION_SUCCESS:
18698                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
18699                        writeRuntimePermissions = true;
18700                        final int appId = ps.appId;
18701                        mHandler.post(new Runnable() {
18702                            @Override
18703                            public void run() {
18704                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
18705                            }
18706                        });
18707                    } break;
18708                }
18709            }
18710        }
18711
18712        // Synchronously write as we are taking permissions away.
18713        if (writeRuntimePermissions) {
18714            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
18715        }
18716
18717        // Synchronously write as we are taking permissions away.
18718        if (writeInstallPermissions) {
18719            mSettings.writeLPr();
18720        }
18721    }
18722
18723    /**
18724     * Remove entries from the keystore daemon. Will only remove it if the
18725     * {@code appId} is valid.
18726     */
18727    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
18728        if (appId < 0) {
18729            return;
18730        }
18731
18732        final KeyStore keyStore = KeyStore.getInstance();
18733        if (keyStore != null) {
18734            if (userId == UserHandle.USER_ALL) {
18735                for (final int individual : sUserManager.getUserIds()) {
18736                    keyStore.clearUid(UserHandle.getUid(individual, appId));
18737                }
18738            } else {
18739                keyStore.clearUid(UserHandle.getUid(userId, appId));
18740            }
18741        } else {
18742            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
18743        }
18744    }
18745
18746    @Override
18747    public void deleteApplicationCacheFiles(final String packageName,
18748            final IPackageDataObserver observer) {
18749        final int userId = UserHandle.getCallingUserId();
18750        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
18751    }
18752
18753    @Override
18754    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
18755            final IPackageDataObserver observer) {
18756        final int callingUid = Binder.getCallingUid();
18757        mContext.enforceCallingOrSelfPermission(
18758                android.Manifest.permission.DELETE_CACHE_FILES, null);
18759        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18760                /* requireFullPermission= */ true, /* checkShell= */ false,
18761                "delete application cache files");
18762        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
18763                android.Manifest.permission.ACCESS_INSTANT_APPS);
18764
18765        final PackageParser.Package pkg;
18766        synchronized (mPackages) {
18767            pkg = mPackages.get(packageName);
18768        }
18769
18770        // Queue up an async operation since the package deletion may take a little while.
18771        mHandler.post(new Runnable() {
18772            public void run() {
18773                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
18774                boolean doClearData = true;
18775                if (ps != null) {
18776                    final boolean targetIsInstantApp =
18777                            ps.getInstantApp(UserHandle.getUserId(callingUid));
18778                    doClearData = !targetIsInstantApp
18779                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
18780                }
18781                if (doClearData) {
18782                    synchronized (mInstallLock) {
18783                        final int flags = StorageManager.FLAG_STORAGE_DE
18784                                | StorageManager.FLAG_STORAGE_CE;
18785                        // We're only clearing cache files, so we don't care if the
18786                        // app is unfrozen and still able to run
18787                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
18788                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18789                    }
18790                    clearExternalStorageDataSync(packageName, userId, false);
18791                }
18792                if (observer != null) {
18793                    try {
18794                        observer.onRemoveCompleted(packageName, true);
18795                    } catch (RemoteException e) {
18796                        Log.i(TAG, "Observer no longer exists.");
18797                    }
18798                }
18799            }
18800        });
18801    }
18802
18803    @Override
18804    public void getPackageSizeInfo(final String packageName, int userHandle,
18805            final IPackageStatsObserver observer) {
18806        throw new UnsupportedOperationException(
18807                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
18808    }
18809
18810    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
18811        final PackageSetting ps;
18812        synchronized (mPackages) {
18813            ps = mSettings.mPackages.get(packageName);
18814            if (ps == null) {
18815                Slog.w(TAG, "Failed to find settings for " + packageName);
18816                return false;
18817            }
18818        }
18819
18820        final String[] packageNames = { packageName };
18821        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
18822        final String[] codePaths = { ps.codePathString };
18823
18824        try {
18825            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
18826                    ps.appId, ceDataInodes, codePaths, stats);
18827
18828            // For now, ignore code size of packages on system partition
18829            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
18830                stats.codeSize = 0;
18831            }
18832
18833            // External clients expect these to be tracked separately
18834            stats.dataSize -= stats.cacheSize;
18835
18836        } catch (InstallerException e) {
18837            Slog.w(TAG, String.valueOf(e));
18838            return false;
18839        }
18840
18841        return true;
18842    }
18843
18844    private int getUidTargetSdkVersionLockedLPr(int uid) {
18845        Object obj = mSettings.getUserIdLPr(uid);
18846        if (obj instanceof SharedUserSetting) {
18847            final SharedUserSetting sus = (SharedUserSetting) obj;
18848            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
18849            final Iterator<PackageSetting> it = sus.packages.iterator();
18850            while (it.hasNext()) {
18851                final PackageSetting ps = it.next();
18852                if (ps.pkg != null) {
18853                    int v = ps.pkg.applicationInfo.targetSdkVersion;
18854                    if (v < vers) vers = v;
18855                }
18856            }
18857            return vers;
18858        } else if (obj instanceof PackageSetting) {
18859            final PackageSetting ps = (PackageSetting) obj;
18860            if (ps.pkg != null) {
18861                return ps.pkg.applicationInfo.targetSdkVersion;
18862            }
18863        }
18864        return Build.VERSION_CODES.CUR_DEVELOPMENT;
18865    }
18866
18867    @Override
18868    public void addPreferredActivity(IntentFilter filter, int match,
18869            ComponentName[] set, ComponentName activity, int userId) {
18870        addPreferredActivityInternal(filter, match, set, activity, true, userId,
18871                "Adding preferred");
18872    }
18873
18874    private void addPreferredActivityInternal(IntentFilter filter, int match,
18875            ComponentName[] set, ComponentName activity, boolean always, int userId,
18876            String opname) {
18877        // writer
18878        int callingUid = Binder.getCallingUid();
18879        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18880                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
18881        if (filter.countActions() == 0) {
18882            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18883            return;
18884        }
18885        synchronized (mPackages) {
18886            if (mContext.checkCallingOrSelfPermission(
18887                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18888                    != PackageManager.PERMISSION_GRANTED) {
18889                if (getUidTargetSdkVersionLockedLPr(callingUid)
18890                        < Build.VERSION_CODES.FROYO) {
18891                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
18892                            + callingUid);
18893                    return;
18894                }
18895                mContext.enforceCallingOrSelfPermission(
18896                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18897            }
18898
18899            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
18900            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
18901                    + userId + ":");
18902            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18903            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
18904            scheduleWritePackageRestrictionsLocked(userId);
18905            postPreferredActivityChangedBroadcast(userId);
18906        }
18907    }
18908
18909    private void postPreferredActivityChangedBroadcast(int userId) {
18910        mHandler.post(() -> {
18911            final IActivityManager am = ActivityManager.getService();
18912            if (am == null) {
18913                return;
18914            }
18915
18916            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
18917            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
18918            try {
18919                am.broadcastIntent(null, intent, null, null,
18920                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
18921                        null, false, false, userId);
18922            } catch (RemoteException e) {
18923            }
18924        });
18925    }
18926
18927    @Override
18928    public void replacePreferredActivity(IntentFilter filter, int match,
18929            ComponentName[] set, ComponentName activity, int userId) {
18930        if (filter.countActions() != 1) {
18931            throw new IllegalArgumentException(
18932                    "replacePreferredActivity expects filter to have only 1 action.");
18933        }
18934        if (filter.countDataAuthorities() != 0
18935                || filter.countDataPaths() != 0
18936                || filter.countDataSchemes() > 1
18937                || filter.countDataTypes() != 0) {
18938            throw new IllegalArgumentException(
18939                    "replacePreferredActivity expects filter to have no data authorities, " +
18940                    "paths, or types; and at most one scheme.");
18941        }
18942
18943        final int callingUid = Binder.getCallingUid();
18944        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18945                true /* requireFullPermission */, false /* checkShell */,
18946                "replace preferred activity");
18947        synchronized (mPackages) {
18948            if (mContext.checkCallingOrSelfPermission(
18949                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18950                    != PackageManager.PERMISSION_GRANTED) {
18951                if (getUidTargetSdkVersionLockedLPr(callingUid)
18952                        < Build.VERSION_CODES.FROYO) {
18953                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
18954                            + Binder.getCallingUid());
18955                    return;
18956                }
18957                mContext.enforceCallingOrSelfPermission(
18958                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18959            }
18960
18961            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18962            if (pir != null) {
18963                // Get all of the existing entries that exactly match this filter.
18964                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
18965                if (existing != null && existing.size() == 1) {
18966                    PreferredActivity cur = existing.get(0);
18967                    if (DEBUG_PREFERRED) {
18968                        Slog.i(TAG, "Checking replace of preferred:");
18969                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18970                        if (!cur.mPref.mAlways) {
18971                            Slog.i(TAG, "  -- CUR; not mAlways!");
18972                        } else {
18973                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
18974                            Slog.i(TAG, "  -- CUR: mSet="
18975                                    + Arrays.toString(cur.mPref.mSetComponents));
18976                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
18977                            Slog.i(TAG, "  -- NEW: mMatch="
18978                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
18979                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
18980                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
18981                        }
18982                    }
18983                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
18984                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
18985                            && cur.mPref.sameSet(set)) {
18986                        // Setting the preferred activity to what it happens to be already
18987                        if (DEBUG_PREFERRED) {
18988                            Slog.i(TAG, "Replacing with same preferred activity "
18989                                    + cur.mPref.mShortComponent + " for user "
18990                                    + userId + ":");
18991                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18992                        }
18993                        return;
18994                    }
18995                }
18996
18997                if (existing != null) {
18998                    if (DEBUG_PREFERRED) {
18999                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19000                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19001                    }
19002                    for (int i = 0; i < existing.size(); i++) {
19003                        PreferredActivity pa = existing.get(i);
19004                        if (DEBUG_PREFERRED) {
19005                            Slog.i(TAG, "Removing existing preferred activity "
19006                                    + pa.mPref.mComponent + ":");
19007                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19008                        }
19009                        pir.removeFilter(pa);
19010                    }
19011                }
19012            }
19013            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19014                    "Replacing preferred");
19015        }
19016    }
19017
19018    @Override
19019    public void clearPackagePreferredActivities(String packageName) {
19020        final int callingUid = Binder.getCallingUid();
19021        if (getInstantAppPackageName(callingUid) != null) {
19022            return;
19023        }
19024        // writer
19025        synchronized (mPackages) {
19026            PackageParser.Package pkg = mPackages.get(packageName);
19027            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
19028                if (mContext.checkCallingOrSelfPermission(
19029                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19030                        != PackageManager.PERMISSION_GRANTED) {
19031                    if (getUidTargetSdkVersionLockedLPr(callingUid)
19032                            < Build.VERSION_CODES.FROYO) {
19033                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19034                                + callingUid);
19035                        return;
19036                    }
19037                    mContext.enforceCallingOrSelfPermission(
19038                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19039                }
19040            }
19041            final PackageSetting ps = mSettings.getPackageLPr(packageName);
19042            if (ps != null
19043                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
19044                return;
19045            }
19046            int user = UserHandle.getCallingUserId();
19047            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19048                scheduleWritePackageRestrictionsLocked(user);
19049            }
19050        }
19051    }
19052
19053    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19054    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19055        ArrayList<PreferredActivity> removed = null;
19056        boolean changed = false;
19057        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19058            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19059            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19060            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19061                continue;
19062            }
19063            Iterator<PreferredActivity> it = pir.filterIterator();
19064            while (it.hasNext()) {
19065                PreferredActivity pa = it.next();
19066                // Mark entry for removal only if it matches the package name
19067                // and the entry is of type "always".
19068                if (packageName == null ||
19069                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19070                                && pa.mPref.mAlways)) {
19071                    if (removed == null) {
19072                        removed = new ArrayList<PreferredActivity>();
19073                    }
19074                    removed.add(pa);
19075                }
19076            }
19077            if (removed != null) {
19078                for (int j=0; j<removed.size(); j++) {
19079                    PreferredActivity pa = removed.get(j);
19080                    pir.removeFilter(pa);
19081                }
19082                changed = true;
19083            }
19084        }
19085        if (changed) {
19086            postPreferredActivityChangedBroadcast(userId);
19087        }
19088        return changed;
19089    }
19090
19091    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19092    private void clearIntentFilterVerificationsLPw(int userId) {
19093        final int packageCount = mPackages.size();
19094        for (int i = 0; i < packageCount; i++) {
19095            PackageParser.Package pkg = mPackages.valueAt(i);
19096            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19097        }
19098    }
19099
19100    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19101    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19102        if (userId == UserHandle.USER_ALL) {
19103            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19104                    sUserManager.getUserIds())) {
19105                for (int oneUserId : sUserManager.getUserIds()) {
19106                    scheduleWritePackageRestrictionsLocked(oneUserId);
19107                }
19108            }
19109        } else {
19110            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19111                scheduleWritePackageRestrictionsLocked(userId);
19112            }
19113        }
19114    }
19115
19116    /** Clears state for all users, and touches intent filter verification policy */
19117    void clearDefaultBrowserIfNeeded(String packageName) {
19118        for (int oneUserId : sUserManager.getUserIds()) {
19119            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19120        }
19121    }
19122
19123    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19124        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19125        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19126            if (packageName.equals(defaultBrowserPackageName)) {
19127                setDefaultBrowserPackageName(null, userId);
19128            }
19129        }
19130    }
19131
19132    @Override
19133    public void resetApplicationPreferences(int userId) {
19134        mContext.enforceCallingOrSelfPermission(
19135                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19136        final long identity = Binder.clearCallingIdentity();
19137        // writer
19138        try {
19139            synchronized (mPackages) {
19140                clearPackagePreferredActivitiesLPw(null, userId);
19141                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19142                // TODO: We have to reset the default SMS and Phone. This requires
19143                // significant refactoring to keep all default apps in the package
19144                // manager (cleaner but more work) or have the services provide
19145                // callbacks to the package manager to request a default app reset.
19146                applyFactoryDefaultBrowserLPw(userId);
19147                clearIntentFilterVerificationsLPw(userId);
19148                primeDomainVerificationsLPw(userId);
19149                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19150                scheduleWritePackageRestrictionsLocked(userId);
19151            }
19152            resetNetworkPolicies(userId);
19153        } finally {
19154            Binder.restoreCallingIdentity(identity);
19155        }
19156    }
19157
19158    @Override
19159    public int getPreferredActivities(List<IntentFilter> outFilters,
19160            List<ComponentName> outActivities, String packageName) {
19161        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19162            return 0;
19163        }
19164        int num = 0;
19165        final int userId = UserHandle.getCallingUserId();
19166        // reader
19167        synchronized (mPackages) {
19168            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19169            if (pir != null) {
19170                final Iterator<PreferredActivity> it = pir.filterIterator();
19171                while (it.hasNext()) {
19172                    final PreferredActivity pa = it.next();
19173                    if (packageName == null
19174                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19175                                    && pa.mPref.mAlways)) {
19176                        if (outFilters != null) {
19177                            outFilters.add(new IntentFilter(pa));
19178                        }
19179                        if (outActivities != null) {
19180                            outActivities.add(pa.mPref.mComponent);
19181                        }
19182                    }
19183                }
19184            }
19185        }
19186
19187        return num;
19188    }
19189
19190    @Override
19191    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19192            int userId) {
19193        int callingUid = Binder.getCallingUid();
19194        if (callingUid != Process.SYSTEM_UID) {
19195            throw new SecurityException(
19196                    "addPersistentPreferredActivity can only be run by the system");
19197        }
19198        if (filter.countActions() == 0) {
19199            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19200            return;
19201        }
19202        synchronized (mPackages) {
19203            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19204                    ":");
19205            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19206            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19207                    new PersistentPreferredActivity(filter, activity));
19208            scheduleWritePackageRestrictionsLocked(userId);
19209            postPreferredActivityChangedBroadcast(userId);
19210        }
19211    }
19212
19213    @Override
19214    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19215        int callingUid = Binder.getCallingUid();
19216        if (callingUid != Process.SYSTEM_UID) {
19217            throw new SecurityException(
19218                    "clearPackagePersistentPreferredActivities can only be run by the system");
19219        }
19220        ArrayList<PersistentPreferredActivity> removed = null;
19221        boolean changed = false;
19222        synchronized (mPackages) {
19223            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19224                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19225                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19226                        .valueAt(i);
19227                if (userId != thisUserId) {
19228                    continue;
19229                }
19230                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19231                while (it.hasNext()) {
19232                    PersistentPreferredActivity ppa = it.next();
19233                    // Mark entry for removal only if it matches the package name.
19234                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19235                        if (removed == null) {
19236                            removed = new ArrayList<PersistentPreferredActivity>();
19237                        }
19238                        removed.add(ppa);
19239                    }
19240                }
19241                if (removed != null) {
19242                    for (int j=0; j<removed.size(); j++) {
19243                        PersistentPreferredActivity ppa = removed.get(j);
19244                        ppir.removeFilter(ppa);
19245                    }
19246                    changed = true;
19247                }
19248            }
19249
19250            if (changed) {
19251                scheduleWritePackageRestrictionsLocked(userId);
19252                postPreferredActivityChangedBroadcast(userId);
19253            }
19254        }
19255    }
19256
19257    /**
19258     * Common machinery for picking apart a restored XML blob and passing
19259     * it to a caller-supplied functor to be applied to the running system.
19260     */
19261    private void restoreFromXml(XmlPullParser parser, int userId,
19262            String expectedStartTag, BlobXmlRestorer functor)
19263            throws IOException, XmlPullParserException {
19264        int type;
19265        while ((type = parser.next()) != XmlPullParser.START_TAG
19266                && type != XmlPullParser.END_DOCUMENT) {
19267        }
19268        if (type != XmlPullParser.START_TAG) {
19269            // oops didn't find a start tag?!
19270            if (DEBUG_BACKUP) {
19271                Slog.e(TAG, "Didn't find start tag during restore");
19272            }
19273            return;
19274        }
19275Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19276        // this is supposed to be TAG_PREFERRED_BACKUP
19277        if (!expectedStartTag.equals(parser.getName())) {
19278            if (DEBUG_BACKUP) {
19279                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19280            }
19281            return;
19282        }
19283
19284        // skip interfering stuff, then we're aligned with the backing implementation
19285        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19286Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19287        functor.apply(parser, userId);
19288    }
19289
19290    private interface BlobXmlRestorer {
19291        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19292    }
19293
19294    /**
19295     * Non-Binder method, support for the backup/restore mechanism: write the
19296     * full set of preferred activities in its canonical XML format.  Returns the
19297     * XML output as a byte array, or null if there is none.
19298     */
19299    @Override
19300    public byte[] getPreferredActivityBackup(int userId) {
19301        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19302            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19303        }
19304
19305        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19306        try {
19307            final XmlSerializer serializer = new FastXmlSerializer();
19308            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19309            serializer.startDocument(null, true);
19310            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19311
19312            synchronized (mPackages) {
19313                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19314            }
19315
19316            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19317            serializer.endDocument();
19318            serializer.flush();
19319        } catch (Exception e) {
19320            if (DEBUG_BACKUP) {
19321                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19322            }
19323            return null;
19324        }
19325
19326        return dataStream.toByteArray();
19327    }
19328
19329    @Override
19330    public void restorePreferredActivities(byte[] backup, int userId) {
19331        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19332            throw new SecurityException("Only the system may call restorePreferredActivities()");
19333        }
19334
19335        try {
19336            final XmlPullParser parser = Xml.newPullParser();
19337            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19338            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19339                    new BlobXmlRestorer() {
19340                        @Override
19341                        public void apply(XmlPullParser parser, int userId)
19342                                throws XmlPullParserException, IOException {
19343                            synchronized (mPackages) {
19344                                mSettings.readPreferredActivitiesLPw(parser, userId);
19345                            }
19346                        }
19347                    } );
19348        } catch (Exception e) {
19349            if (DEBUG_BACKUP) {
19350                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19351            }
19352        }
19353    }
19354
19355    /**
19356     * Non-Binder method, support for the backup/restore mechanism: write the
19357     * default browser (etc) settings in its canonical XML format.  Returns the default
19358     * browser XML representation as a byte array, or null if there is none.
19359     */
19360    @Override
19361    public byte[] getDefaultAppsBackup(int userId) {
19362        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19363            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19364        }
19365
19366        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19367        try {
19368            final XmlSerializer serializer = new FastXmlSerializer();
19369            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19370            serializer.startDocument(null, true);
19371            serializer.startTag(null, TAG_DEFAULT_APPS);
19372
19373            synchronized (mPackages) {
19374                mSettings.writeDefaultAppsLPr(serializer, userId);
19375            }
19376
19377            serializer.endTag(null, TAG_DEFAULT_APPS);
19378            serializer.endDocument();
19379            serializer.flush();
19380        } catch (Exception e) {
19381            if (DEBUG_BACKUP) {
19382                Slog.e(TAG, "Unable to write default apps for backup", e);
19383            }
19384            return null;
19385        }
19386
19387        return dataStream.toByteArray();
19388    }
19389
19390    @Override
19391    public void restoreDefaultApps(byte[] backup, int userId) {
19392        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19393            throw new SecurityException("Only the system may call restoreDefaultApps()");
19394        }
19395
19396        try {
19397            final XmlPullParser parser = Xml.newPullParser();
19398            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19399            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19400                    new BlobXmlRestorer() {
19401                        @Override
19402                        public void apply(XmlPullParser parser, int userId)
19403                                throws XmlPullParserException, IOException {
19404                            synchronized (mPackages) {
19405                                mSettings.readDefaultAppsLPw(parser, userId);
19406                            }
19407                        }
19408                    } );
19409        } catch (Exception e) {
19410            if (DEBUG_BACKUP) {
19411                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19412            }
19413        }
19414    }
19415
19416    @Override
19417    public byte[] getIntentFilterVerificationBackup(int userId) {
19418        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19419            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19420        }
19421
19422        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19423        try {
19424            final XmlSerializer serializer = new FastXmlSerializer();
19425            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19426            serializer.startDocument(null, true);
19427            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19428
19429            synchronized (mPackages) {
19430                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19431            }
19432
19433            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19434            serializer.endDocument();
19435            serializer.flush();
19436        } catch (Exception e) {
19437            if (DEBUG_BACKUP) {
19438                Slog.e(TAG, "Unable to write default apps for backup", e);
19439            }
19440            return null;
19441        }
19442
19443        return dataStream.toByteArray();
19444    }
19445
19446    @Override
19447    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19448        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19449            throw new SecurityException("Only the system may call restorePreferredActivities()");
19450        }
19451
19452        try {
19453            final XmlPullParser parser = Xml.newPullParser();
19454            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19455            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19456                    new BlobXmlRestorer() {
19457                        @Override
19458                        public void apply(XmlPullParser parser, int userId)
19459                                throws XmlPullParserException, IOException {
19460                            synchronized (mPackages) {
19461                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19462                                mSettings.writeLPr();
19463                            }
19464                        }
19465                    } );
19466        } catch (Exception e) {
19467            if (DEBUG_BACKUP) {
19468                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19469            }
19470        }
19471    }
19472
19473    @Override
19474    public byte[] getPermissionGrantBackup(int userId) {
19475        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19476            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19477        }
19478
19479        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19480        try {
19481            final XmlSerializer serializer = new FastXmlSerializer();
19482            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19483            serializer.startDocument(null, true);
19484            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19485
19486            synchronized (mPackages) {
19487                serializeRuntimePermissionGrantsLPr(serializer, userId);
19488            }
19489
19490            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19491            serializer.endDocument();
19492            serializer.flush();
19493        } catch (Exception e) {
19494            if (DEBUG_BACKUP) {
19495                Slog.e(TAG, "Unable to write default apps for backup", e);
19496            }
19497            return null;
19498        }
19499
19500        return dataStream.toByteArray();
19501    }
19502
19503    @Override
19504    public void restorePermissionGrants(byte[] backup, int userId) {
19505        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19506            throw new SecurityException("Only the system may call restorePermissionGrants()");
19507        }
19508
19509        try {
19510            final XmlPullParser parser = Xml.newPullParser();
19511            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19512            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19513                    new BlobXmlRestorer() {
19514                        @Override
19515                        public void apply(XmlPullParser parser, int userId)
19516                                throws XmlPullParserException, IOException {
19517                            synchronized (mPackages) {
19518                                processRestoredPermissionGrantsLPr(parser, userId);
19519                            }
19520                        }
19521                    } );
19522        } catch (Exception e) {
19523            if (DEBUG_BACKUP) {
19524                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19525            }
19526        }
19527    }
19528
19529    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19530            throws IOException {
19531        serializer.startTag(null, TAG_ALL_GRANTS);
19532
19533        final int N = mSettings.mPackages.size();
19534        for (int i = 0; i < N; i++) {
19535            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19536            boolean pkgGrantsKnown = false;
19537
19538            PermissionsState packagePerms = ps.getPermissionsState();
19539
19540            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19541                final int grantFlags = state.getFlags();
19542                // only look at grants that are not system/policy fixed
19543                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19544                    final boolean isGranted = state.isGranted();
19545                    // And only back up the user-twiddled state bits
19546                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19547                        final String packageName = mSettings.mPackages.keyAt(i);
19548                        if (!pkgGrantsKnown) {
19549                            serializer.startTag(null, TAG_GRANT);
19550                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19551                            pkgGrantsKnown = true;
19552                        }
19553
19554                        final boolean userSet =
19555                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19556                        final boolean userFixed =
19557                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19558                        final boolean revoke =
19559                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19560
19561                        serializer.startTag(null, TAG_PERMISSION);
19562                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19563                        if (isGranted) {
19564                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19565                        }
19566                        if (userSet) {
19567                            serializer.attribute(null, ATTR_USER_SET, "true");
19568                        }
19569                        if (userFixed) {
19570                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19571                        }
19572                        if (revoke) {
19573                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19574                        }
19575                        serializer.endTag(null, TAG_PERMISSION);
19576                    }
19577                }
19578            }
19579
19580            if (pkgGrantsKnown) {
19581                serializer.endTag(null, TAG_GRANT);
19582            }
19583        }
19584
19585        serializer.endTag(null, TAG_ALL_GRANTS);
19586    }
19587
19588    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19589            throws XmlPullParserException, IOException {
19590        String pkgName = null;
19591        int outerDepth = parser.getDepth();
19592        int type;
19593        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19594                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19595            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19596                continue;
19597            }
19598
19599            final String tagName = parser.getName();
19600            if (tagName.equals(TAG_GRANT)) {
19601                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19602                if (DEBUG_BACKUP) {
19603                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19604                }
19605            } else if (tagName.equals(TAG_PERMISSION)) {
19606
19607                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19608                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19609
19610                int newFlagSet = 0;
19611                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19612                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19613                }
19614                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19615                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19616                }
19617                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19618                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19619                }
19620                if (DEBUG_BACKUP) {
19621                    Slog.v(TAG, "  + Restoring grant:"
19622                            + " pkg=" + pkgName
19623                            + " perm=" + permName
19624                            + " granted=" + isGranted
19625                            + " bits=0x" + Integer.toHexString(newFlagSet));
19626                }
19627                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19628                if (ps != null) {
19629                    // Already installed so we apply the grant immediately
19630                    if (DEBUG_BACKUP) {
19631                        Slog.v(TAG, "        + already installed; applying");
19632                    }
19633                    PermissionsState perms = ps.getPermissionsState();
19634                    BasePermission bp =
19635                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
19636                    if (bp != null) {
19637                        if (isGranted) {
19638                            perms.grantRuntimePermission(bp, userId);
19639                        }
19640                        if (newFlagSet != 0) {
19641                            perms.updatePermissionFlags(
19642                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
19643                        }
19644                    }
19645                } else {
19646                    // Need to wait for post-restore install to apply the grant
19647                    if (DEBUG_BACKUP) {
19648                        Slog.v(TAG, "        - not yet installed; saving for later");
19649                    }
19650                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
19651                            isGranted, newFlagSet, userId);
19652                }
19653            } else {
19654                PackageManagerService.reportSettingsProblem(Log.WARN,
19655                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
19656                XmlUtils.skipCurrentTag(parser);
19657            }
19658        }
19659
19660        scheduleWriteSettingsLocked();
19661        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19662    }
19663
19664    @Override
19665    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
19666            int sourceUserId, int targetUserId, int flags) {
19667        mContext.enforceCallingOrSelfPermission(
19668                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19669        int callingUid = Binder.getCallingUid();
19670        enforceOwnerRights(ownerPackage, callingUid);
19671        PackageManagerServiceUtils.enforceShellRestriction(
19672                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19673        if (intentFilter.countActions() == 0) {
19674            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
19675            return;
19676        }
19677        synchronized (mPackages) {
19678            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
19679                    ownerPackage, targetUserId, flags);
19680            CrossProfileIntentResolver resolver =
19681                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19682            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
19683            // We have all those whose filter is equal. Now checking if the rest is equal as well.
19684            if (existing != null) {
19685                int size = existing.size();
19686                for (int i = 0; i < size; i++) {
19687                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
19688                        return;
19689                    }
19690                }
19691            }
19692            resolver.addFilter(newFilter);
19693            scheduleWritePackageRestrictionsLocked(sourceUserId);
19694        }
19695    }
19696
19697    @Override
19698    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
19699        mContext.enforceCallingOrSelfPermission(
19700                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19701        final int callingUid = Binder.getCallingUid();
19702        enforceOwnerRights(ownerPackage, callingUid);
19703        PackageManagerServiceUtils.enforceShellRestriction(
19704                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19705        synchronized (mPackages) {
19706            CrossProfileIntentResolver resolver =
19707                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19708            ArraySet<CrossProfileIntentFilter> set =
19709                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
19710            for (CrossProfileIntentFilter filter : set) {
19711                if (filter.getOwnerPackage().equals(ownerPackage)) {
19712                    resolver.removeFilter(filter);
19713                }
19714            }
19715            scheduleWritePackageRestrictionsLocked(sourceUserId);
19716        }
19717    }
19718
19719    // Enforcing that callingUid is owning pkg on userId
19720    private void enforceOwnerRights(String pkg, int callingUid) {
19721        // The system owns everything.
19722        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19723            return;
19724        }
19725        final int callingUserId = UserHandle.getUserId(callingUid);
19726        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
19727        if (pi == null) {
19728            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
19729                    + callingUserId);
19730        }
19731        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
19732            throw new SecurityException("Calling uid " + callingUid
19733                    + " does not own package " + pkg);
19734        }
19735    }
19736
19737    @Override
19738    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
19739        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19740            return null;
19741        }
19742        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
19743    }
19744
19745    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
19746        UserManagerService ums = UserManagerService.getInstance();
19747        if (ums != null) {
19748            final UserInfo parent = ums.getProfileParent(userId);
19749            final int launcherUid = (parent != null) ? parent.id : userId;
19750            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
19751            if (launcherComponent != null) {
19752                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
19753                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
19754                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
19755                        .setPackage(launcherComponent.getPackageName());
19756                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
19757            }
19758        }
19759    }
19760
19761    /**
19762     * Report the 'Home' activity which is currently set as "always use this one". If non is set
19763     * then reports the most likely home activity or null if there are more than one.
19764     */
19765    private ComponentName getDefaultHomeActivity(int userId) {
19766        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
19767        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
19768        if (cn != null) {
19769            return cn;
19770        }
19771
19772        // Find the launcher with the highest priority and return that component if there are no
19773        // other home activity with the same priority.
19774        int lastPriority = Integer.MIN_VALUE;
19775        ComponentName lastComponent = null;
19776        final int size = allHomeCandidates.size();
19777        for (int i = 0; i < size; i++) {
19778            final ResolveInfo ri = allHomeCandidates.get(i);
19779            if (ri.priority > lastPriority) {
19780                lastComponent = ri.activityInfo.getComponentName();
19781                lastPriority = ri.priority;
19782            } else if (ri.priority == lastPriority) {
19783                // Two components found with same priority.
19784                lastComponent = null;
19785            }
19786        }
19787        return lastComponent;
19788    }
19789
19790    private Intent getHomeIntent() {
19791        Intent intent = new Intent(Intent.ACTION_MAIN);
19792        intent.addCategory(Intent.CATEGORY_HOME);
19793        intent.addCategory(Intent.CATEGORY_DEFAULT);
19794        return intent;
19795    }
19796
19797    private IntentFilter getHomeFilter() {
19798        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
19799        filter.addCategory(Intent.CATEGORY_HOME);
19800        filter.addCategory(Intent.CATEGORY_DEFAULT);
19801        return filter;
19802    }
19803
19804    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19805            int userId) {
19806        Intent intent  = getHomeIntent();
19807        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
19808                PackageManager.GET_META_DATA, userId);
19809        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
19810                true, false, false, userId);
19811
19812        allHomeCandidates.clear();
19813        if (list != null) {
19814            for (ResolveInfo ri : list) {
19815                allHomeCandidates.add(ri);
19816            }
19817        }
19818        return (preferred == null || preferred.activityInfo == null)
19819                ? null
19820                : new ComponentName(preferred.activityInfo.packageName,
19821                        preferred.activityInfo.name);
19822    }
19823
19824    @Override
19825    public void setHomeActivity(ComponentName comp, int userId) {
19826        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19827            return;
19828        }
19829        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
19830        getHomeActivitiesAsUser(homeActivities, userId);
19831
19832        boolean found = false;
19833
19834        final int size = homeActivities.size();
19835        final ComponentName[] set = new ComponentName[size];
19836        for (int i = 0; i < size; i++) {
19837            final ResolveInfo candidate = homeActivities.get(i);
19838            final ActivityInfo info = candidate.activityInfo;
19839            final ComponentName activityName = new ComponentName(info.packageName, info.name);
19840            set[i] = activityName;
19841            if (!found && activityName.equals(comp)) {
19842                found = true;
19843            }
19844        }
19845        if (!found) {
19846            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
19847                    + userId);
19848        }
19849        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
19850                set, comp, userId);
19851    }
19852
19853    private @Nullable String getSetupWizardPackageName() {
19854        final Intent intent = new Intent(Intent.ACTION_MAIN);
19855        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
19856
19857        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19858                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19859                        | MATCH_DISABLED_COMPONENTS,
19860                UserHandle.myUserId());
19861        if (matches.size() == 1) {
19862            return matches.get(0).getComponentInfo().packageName;
19863        } else {
19864            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
19865                    + ": matches=" + matches);
19866            return null;
19867        }
19868    }
19869
19870    private @Nullable String getStorageManagerPackageName() {
19871        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
19872
19873        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19874                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19875                        | MATCH_DISABLED_COMPONENTS,
19876                UserHandle.myUserId());
19877        if (matches.size() == 1) {
19878            return matches.get(0).getComponentInfo().packageName;
19879        } else {
19880            Slog.e(TAG, "There should probably be exactly one storage manager; found "
19881                    + matches.size() + ": matches=" + matches);
19882            return null;
19883        }
19884    }
19885
19886    @Override
19887    public void setApplicationEnabledSetting(String appPackageName,
19888            int newState, int flags, int userId, String callingPackage) {
19889        if (!sUserManager.exists(userId)) return;
19890        if (callingPackage == null) {
19891            callingPackage = Integer.toString(Binder.getCallingUid());
19892        }
19893        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
19894    }
19895
19896    @Override
19897    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
19898        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
19899        synchronized (mPackages) {
19900            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
19901            if (pkgSetting != null) {
19902                pkgSetting.setUpdateAvailable(updateAvailable);
19903            }
19904        }
19905    }
19906
19907    @Override
19908    public void setComponentEnabledSetting(ComponentName componentName,
19909            int newState, int flags, int userId) {
19910        if (!sUserManager.exists(userId)) return;
19911        setEnabledSetting(componentName.getPackageName(),
19912                componentName.getClassName(), newState, flags, userId, null);
19913    }
19914
19915    private void setEnabledSetting(final String packageName, String className, int newState,
19916            final int flags, int userId, String callingPackage) {
19917        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
19918              || newState == COMPONENT_ENABLED_STATE_ENABLED
19919              || newState == COMPONENT_ENABLED_STATE_DISABLED
19920              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19921              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
19922            throw new IllegalArgumentException("Invalid new component state: "
19923                    + newState);
19924        }
19925        PackageSetting pkgSetting;
19926        final int callingUid = Binder.getCallingUid();
19927        final int permission;
19928        if (callingUid == Process.SYSTEM_UID) {
19929            permission = PackageManager.PERMISSION_GRANTED;
19930        } else {
19931            permission = mContext.checkCallingOrSelfPermission(
19932                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19933        }
19934        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19935                false /* requireFullPermission */, true /* checkShell */, "set enabled");
19936        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19937        boolean sendNow = false;
19938        boolean isApp = (className == null);
19939        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
19940        String componentName = isApp ? packageName : className;
19941        int packageUid = -1;
19942        ArrayList<String> components;
19943
19944        // reader
19945        synchronized (mPackages) {
19946            pkgSetting = mSettings.mPackages.get(packageName);
19947            if (pkgSetting == null) {
19948                if (!isCallerInstantApp) {
19949                    if (className == null) {
19950                        throw new IllegalArgumentException("Unknown package: " + packageName);
19951                    }
19952                    throw new IllegalArgumentException(
19953                            "Unknown component: " + packageName + "/" + className);
19954                } else {
19955                    // throw SecurityException to prevent leaking package information
19956                    throw new SecurityException(
19957                            "Attempt to change component state; "
19958                            + "pid=" + Binder.getCallingPid()
19959                            + ", uid=" + callingUid
19960                            + (className == null
19961                                    ? ", package=" + packageName
19962                                    : ", component=" + packageName + "/" + className));
19963                }
19964            }
19965        }
19966
19967        // Limit who can change which apps
19968        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
19969            // Don't allow apps that don't have permission to modify other apps
19970            if (!allowedByPermission
19971                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
19972                throw new SecurityException(
19973                        "Attempt to change component state; "
19974                        + "pid=" + Binder.getCallingPid()
19975                        + ", uid=" + callingUid
19976                        + (className == null
19977                                ? ", package=" + packageName
19978                                : ", component=" + packageName + "/" + className));
19979            }
19980            // Don't allow changing protected packages.
19981            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
19982                throw new SecurityException("Cannot disable a protected package: " + packageName);
19983            }
19984        }
19985
19986        synchronized (mPackages) {
19987            if (callingUid == Process.SHELL_UID
19988                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
19989                // Shell can only change whole packages between ENABLED and DISABLED_USER states
19990                // unless it is a test package.
19991                int oldState = pkgSetting.getEnabled(userId);
19992                if (className == null
19993                        &&
19994                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
19995                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
19996                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
19997                        &&
19998                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19999                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
20000                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20001                    // ok
20002                } else {
20003                    throw new SecurityException(
20004                            "Shell cannot change component state for " + packageName + "/"
20005                                    + className + " to " + newState);
20006                }
20007            }
20008        }
20009        if (className == null) {
20010            // We're dealing with an application/package level state change
20011            synchronized (mPackages) {
20012                if (pkgSetting.getEnabled(userId) == newState) {
20013                    // Nothing to do
20014                    return;
20015                }
20016            }
20017            // If we're enabling a system stub, there's a little more work to do.
20018            // Prior to enabling the package, we need to decompress the APK(s) to the
20019            // data partition and then replace the version on the system partition.
20020            final PackageParser.Package deletedPkg = pkgSetting.pkg;
20021            final boolean isSystemStub = deletedPkg.isStub
20022                    && deletedPkg.isSystem();
20023            if (isSystemStub
20024                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20025                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
20026                final File codePath = decompressPackage(deletedPkg);
20027                if (codePath == null) {
20028                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
20029                    return;
20030                }
20031                // TODO remove direct parsing of the package object during internal cleanup
20032                // of scan package
20033                // We need to call parse directly here for no other reason than we need
20034                // the new package in order to disable the old one [we use the information
20035                // for some internal optimization to optionally create a new package setting
20036                // object on replace]. However, we can't get the package from the scan
20037                // because the scan modifies live structures and we need to remove the
20038                // old [system] package from the system before a scan can be attempted.
20039                // Once scan is indempotent we can remove this parse and use the package
20040                // object we scanned, prior to adding it to package settings.
20041                final PackageParser pp = new PackageParser();
20042                pp.setSeparateProcesses(mSeparateProcesses);
20043                pp.setDisplayMetrics(mMetrics);
20044                pp.setCallback(mPackageParserCallback);
20045                final PackageParser.Package tmpPkg;
20046                try {
20047                    final @ParseFlags int parseFlags = mDefParseFlags
20048                            | PackageParser.PARSE_MUST_BE_APK
20049                            | PackageParser.PARSE_IS_SYSTEM_DIR;
20050                    tmpPkg = pp.parsePackage(codePath, parseFlags);
20051                } catch (PackageParserException e) {
20052                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
20053                    return;
20054                }
20055                synchronized (mInstallLock) {
20056                    // Disable the stub and remove any package entries
20057                    removePackageLI(deletedPkg, true);
20058                    synchronized (mPackages) {
20059                        disableSystemPackageLPw(deletedPkg, tmpPkg);
20060                    }
20061                    final PackageParser.Package pkg;
20062                    try (PackageFreezer freezer =
20063                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20064                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
20065                                | PackageParser.PARSE_ENFORCE_CODE;
20066                        pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
20067                                0 /*currentTime*/, null /*user*/);
20068                        prepareAppDataAfterInstallLIF(pkg);
20069                        synchronized (mPackages) {
20070                            try {
20071                                updateSharedLibrariesLPr(pkg, null);
20072                            } catch (PackageManagerException e) {
20073                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
20074                            }
20075                            mPermissionManager.updatePermissions(
20076                                    pkg.packageName, pkg, true, mPackages.values(),
20077                                    mPermissionCallback);
20078                            mSettings.writeLPr();
20079                        }
20080                    } catch (PackageManagerException e) {
20081                        // Whoops! Something went wrong; try to roll back to the stub
20082                        Slog.w(TAG, "Failed to install compressed system package:"
20083                                + pkgSetting.name, e);
20084                        // Remove the failed install
20085                        removeCodePathLI(codePath);
20086
20087                        // Install the system package
20088                        try (PackageFreezer freezer =
20089                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20090                            synchronized (mPackages) {
20091                                // NOTE: The system package always needs to be enabled; even
20092                                // if it's for a compressed stub. If we don't, installing the
20093                                // system package fails during scan [scanning checks the disabled
20094                                // packages]. We will reverse this later, after we've "installed"
20095                                // the stub.
20096                                // This leaves us in a fragile state; the stub should never be
20097                                // enabled, so, cross your fingers and hope nothing goes wrong
20098                                // until we can disable the package later.
20099                                enableSystemPackageLPw(deletedPkg);
20100                            }
20101                            installPackageFromSystemLIF(deletedPkg.codePath,
20102                                    false /*isPrivileged*/, null /*allUserHandles*/,
20103                                    null /*origUserHandles*/, null /*origPermissionsState*/,
20104                                    true /*writeSettings*/);
20105                        } catch (PackageManagerException pme) {
20106                            Slog.w(TAG, "Failed to restore system package:"
20107                                    + deletedPkg.packageName, pme);
20108                        } finally {
20109                            synchronized (mPackages) {
20110                                mSettings.disableSystemPackageLPw(
20111                                        deletedPkg.packageName, true /*replaced*/);
20112                                mSettings.writeLPr();
20113                            }
20114                        }
20115                        return;
20116                    }
20117                    clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
20118                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20119                    clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
20120                    mDexManager.notifyPackageUpdated(pkg.packageName,
20121                            pkg.baseCodePath, pkg.splitCodePaths);
20122                }
20123            }
20124            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20125                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20126                // Don't care about who enables an app.
20127                callingPackage = null;
20128            }
20129            synchronized (mPackages) {
20130                pkgSetting.setEnabled(newState, userId, callingPackage);
20131            }
20132        } else {
20133            synchronized (mPackages) {
20134                // We're dealing with a component level state change
20135                // First, verify that this is a valid class name.
20136                PackageParser.Package pkg = pkgSetting.pkg;
20137                if (pkg == null || !pkg.hasComponentClassName(className)) {
20138                    if (pkg != null &&
20139                            pkg.applicationInfo.targetSdkVersion >=
20140                                    Build.VERSION_CODES.JELLY_BEAN) {
20141                        throw new IllegalArgumentException("Component class " + className
20142                                + " does not exist in " + packageName);
20143                    } else {
20144                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20145                                + className + " does not exist in " + packageName);
20146                    }
20147                }
20148                switch (newState) {
20149                    case COMPONENT_ENABLED_STATE_ENABLED:
20150                        if (!pkgSetting.enableComponentLPw(className, userId)) {
20151                            return;
20152                        }
20153                        break;
20154                    case COMPONENT_ENABLED_STATE_DISABLED:
20155                        if (!pkgSetting.disableComponentLPw(className, userId)) {
20156                            return;
20157                        }
20158                        break;
20159                    case COMPONENT_ENABLED_STATE_DEFAULT:
20160                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
20161                            return;
20162                        }
20163                        break;
20164                    default:
20165                        Slog.e(TAG, "Invalid new component state: " + newState);
20166                        return;
20167                }
20168            }
20169        }
20170        synchronized (mPackages) {
20171            scheduleWritePackageRestrictionsLocked(userId);
20172            updateSequenceNumberLP(pkgSetting, new int[] { userId });
20173            final long callingId = Binder.clearCallingIdentity();
20174            try {
20175                updateInstantAppInstallerLocked(packageName);
20176            } finally {
20177                Binder.restoreCallingIdentity(callingId);
20178            }
20179            components = mPendingBroadcasts.get(userId, packageName);
20180            final boolean newPackage = components == null;
20181            if (newPackage) {
20182                components = new ArrayList<String>();
20183            }
20184            if (!components.contains(componentName)) {
20185                components.add(componentName);
20186            }
20187            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20188                sendNow = true;
20189                // Purge entry from pending broadcast list if another one exists already
20190                // since we are sending one right away.
20191                mPendingBroadcasts.remove(userId, packageName);
20192            } else {
20193                if (newPackage) {
20194                    mPendingBroadcasts.put(userId, packageName, components);
20195                }
20196                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20197                    // Schedule a message
20198                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20199                }
20200            }
20201        }
20202
20203        long callingId = Binder.clearCallingIdentity();
20204        try {
20205            if (sendNow) {
20206                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20207                sendPackageChangedBroadcast(packageName,
20208                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20209            }
20210        } finally {
20211            Binder.restoreCallingIdentity(callingId);
20212        }
20213    }
20214
20215    @Override
20216    public void flushPackageRestrictionsAsUser(int userId) {
20217        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20218            return;
20219        }
20220        if (!sUserManager.exists(userId)) {
20221            return;
20222        }
20223        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20224                false /* checkShell */, "flushPackageRestrictions");
20225        synchronized (mPackages) {
20226            mSettings.writePackageRestrictionsLPr(userId);
20227            mDirtyUsers.remove(userId);
20228            if (mDirtyUsers.isEmpty()) {
20229                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20230            }
20231        }
20232    }
20233
20234    private void sendPackageChangedBroadcast(String packageName,
20235            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20236        if (DEBUG_INSTALL)
20237            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20238                    + componentNames);
20239        Bundle extras = new Bundle(4);
20240        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20241        String nameList[] = new String[componentNames.size()];
20242        componentNames.toArray(nameList);
20243        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20244        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20245        extras.putInt(Intent.EXTRA_UID, packageUid);
20246        // If this is not reporting a change of the overall package, then only send it
20247        // to registered receivers.  We don't want to launch a swath of apps for every
20248        // little component state change.
20249        final int flags = !componentNames.contains(packageName)
20250                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20251        final int userId = UserHandle.getUserId(packageUid);
20252        final boolean isInstantApp = isInstantApp(packageName, userId);
20253        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
20254        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
20255        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20256                userIds, instantUserIds);
20257    }
20258
20259    @Override
20260    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20261        if (!sUserManager.exists(userId)) return;
20262        final int callingUid = Binder.getCallingUid();
20263        if (getInstantAppPackageName(callingUid) != null) {
20264            return;
20265        }
20266        final int permission = mContext.checkCallingOrSelfPermission(
20267                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20268        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20269        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20270                true /* requireFullPermission */, true /* checkShell */, "stop package");
20271        // writer
20272        synchronized (mPackages) {
20273            final PackageSetting ps = mSettings.mPackages.get(packageName);
20274            if (!filterAppAccessLPr(ps, callingUid, userId)
20275                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20276                            allowedByPermission, callingUid, userId)) {
20277                scheduleWritePackageRestrictionsLocked(userId);
20278            }
20279        }
20280    }
20281
20282    @Override
20283    public String getInstallerPackageName(String packageName) {
20284        final int callingUid = Binder.getCallingUid();
20285        if (getInstantAppPackageName(callingUid) != null) {
20286            return null;
20287        }
20288        // reader
20289        synchronized (mPackages) {
20290            final PackageSetting ps = mSettings.mPackages.get(packageName);
20291            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20292                return null;
20293            }
20294            return mSettings.getInstallerPackageNameLPr(packageName);
20295        }
20296    }
20297
20298    public boolean isOrphaned(String packageName) {
20299        // reader
20300        synchronized (mPackages) {
20301            return mSettings.isOrphaned(packageName);
20302        }
20303    }
20304
20305    @Override
20306    public int getApplicationEnabledSetting(String packageName, int userId) {
20307        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20308        int callingUid = Binder.getCallingUid();
20309        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20310                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20311        // reader
20312        synchronized (mPackages) {
20313            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
20314                return COMPONENT_ENABLED_STATE_DISABLED;
20315            }
20316            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20317        }
20318    }
20319
20320    @Override
20321    public int getComponentEnabledSetting(ComponentName component, int userId) {
20322        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20323        int callingUid = Binder.getCallingUid();
20324        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20325                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
20326        synchronized (mPackages) {
20327            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
20328                    component, TYPE_UNKNOWN, userId)) {
20329                return COMPONENT_ENABLED_STATE_DISABLED;
20330            }
20331            return mSettings.getComponentEnabledSettingLPr(component, userId);
20332        }
20333    }
20334
20335    @Override
20336    public void enterSafeMode() {
20337        enforceSystemOrRoot("Only the system can request entering safe mode");
20338
20339        if (!mSystemReady) {
20340            mSafeMode = true;
20341        }
20342    }
20343
20344    @Override
20345    public void systemReady() {
20346        enforceSystemOrRoot("Only the system can claim the system is ready");
20347
20348        mSystemReady = true;
20349        final ContentResolver resolver = mContext.getContentResolver();
20350        ContentObserver co = new ContentObserver(mHandler) {
20351            @Override
20352            public void onChange(boolean selfChange) {
20353                mEphemeralAppsDisabled =
20354                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20355                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20356            }
20357        };
20358        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20359                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20360                false, co, UserHandle.USER_SYSTEM);
20361        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20362                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20363        co.onChange(true);
20364
20365        // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to
20366        // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once
20367        // it is done.
20368        ContentObserver privAppOobObserver = new ContentObserver(mHandler) {
20369            @Override
20370            public void onChange(boolean selfChange) {
20371                int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0);
20372                SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB,
20373                        oobEnabled == 1 ? "true" : "false");
20374            }
20375        };
20376        mContext.getContentResolver().registerContentObserver(
20377                Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver,
20378                UserHandle.USER_SYSTEM);
20379        // At boot, restore the value from the setting, which persists across reboot.
20380        privAppOobObserver.onChange(true);
20381
20382        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20383        // disabled after already being started.
20384        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20385                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20386
20387        // Read the compatibilty setting when the system is ready.
20388        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20389                mContext.getContentResolver(),
20390                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20391        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20392        if (DEBUG_SETTINGS) {
20393            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20394        }
20395
20396        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20397
20398        synchronized (mPackages) {
20399            // Verify that all of the preferred activity components actually
20400            // exist.  It is possible for applications to be updated and at
20401            // that point remove a previously declared activity component that
20402            // had been set as a preferred activity.  We try to clean this up
20403            // the next time we encounter that preferred activity, but it is
20404            // possible for the user flow to never be able to return to that
20405            // situation so here we do a sanity check to make sure we haven't
20406            // left any junk around.
20407            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20408            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20409                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20410                removed.clear();
20411                for (PreferredActivity pa : pir.filterSet()) {
20412                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20413                        removed.add(pa);
20414                    }
20415                }
20416                if (removed.size() > 0) {
20417                    for (int r=0; r<removed.size(); r++) {
20418                        PreferredActivity pa = removed.get(r);
20419                        Slog.w(TAG, "Removing dangling preferred activity: "
20420                                + pa.mPref.mComponent);
20421                        pir.removeFilter(pa);
20422                    }
20423                    mSettings.writePackageRestrictionsLPr(
20424                            mSettings.mPreferredActivities.keyAt(i));
20425                }
20426            }
20427
20428            for (int userId : UserManagerService.getInstance().getUserIds()) {
20429                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20430                    grantPermissionsUserIds = ArrayUtils.appendInt(
20431                            grantPermissionsUserIds, userId);
20432                }
20433            }
20434        }
20435        sUserManager.systemReady();
20436        // If we upgraded grant all default permissions before kicking off.
20437        for (int userId : grantPermissionsUserIds) {
20438            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20439        }
20440
20441        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20442            // If we did not grant default permissions, we preload from this the
20443            // default permission exceptions lazily to ensure we don't hit the
20444            // disk on a new user creation.
20445            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20446        }
20447
20448        // Now that we've scanned all packages, and granted any default
20449        // permissions, ensure permissions are updated. Beware of dragons if you
20450        // try optimizing this.
20451        synchronized (mPackages) {
20452            mPermissionManager.updateAllPermissions(
20453                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
20454                    mPermissionCallback);
20455        }
20456
20457        // Kick off any messages waiting for system ready
20458        if (mPostSystemReadyMessages != null) {
20459            for (Message msg : mPostSystemReadyMessages) {
20460                msg.sendToTarget();
20461            }
20462            mPostSystemReadyMessages = null;
20463        }
20464
20465        // Watch for external volumes that come and go over time
20466        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20467        storage.registerListener(mStorageListener);
20468
20469        mInstallerService.systemReady();
20470        mPackageDexOptimizer.systemReady();
20471
20472        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20473                StorageManagerInternal.class);
20474        StorageManagerInternal.addExternalStoragePolicy(
20475                new StorageManagerInternal.ExternalStorageMountPolicy() {
20476            @Override
20477            public int getMountMode(int uid, String packageName) {
20478                if (Process.isIsolated(uid)) {
20479                    return Zygote.MOUNT_EXTERNAL_NONE;
20480                }
20481                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
20482                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20483                }
20484                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20485                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20486                }
20487                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20488                    return Zygote.MOUNT_EXTERNAL_READ;
20489                }
20490                return Zygote.MOUNT_EXTERNAL_WRITE;
20491            }
20492
20493            @Override
20494            public boolean hasExternalStorage(int uid, String packageName) {
20495                return true;
20496            }
20497        });
20498
20499        // Now that we're mostly running, clean up stale users and apps
20500        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20501        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20502
20503        mPermissionManager.systemReady();
20504    }
20505
20506    public void waitForAppDataPrepared() {
20507        if (mPrepareAppDataFuture == null) {
20508            return;
20509        }
20510        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20511        mPrepareAppDataFuture = null;
20512    }
20513
20514    @Override
20515    public boolean isSafeMode() {
20516        // allow instant applications
20517        return mSafeMode;
20518    }
20519
20520    @Override
20521    public boolean hasSystemUidErrors() {
20522        // allow instant applications
20523        return mHasSystemUidErrors;
20524    }
20525
20526    static String arrayToString(int[] array) {
20527        StringBuffer buf = new StringBuffer(128);
20528        buf.append('[');
20529        if (array != null) {
20530            for (int i=0; i<array.length; i++) {
20531                if (i > 0) buf.append(", ");
20532                buf.append(array[i]);
20533            }
20534        }
20535        buf.append(']');
20536        return buf.toString();
20537    }
20538
20539    @Override
20540    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20541            FileDescriptor err, String[] args, ShellCallback callback,
20542            ResultReceiver resultReceiver) {
20543        (new PackageManagerShellCommand(this)).exec(
20544                this, in, out, err, args, callback, resultReceiver);
20545    }
20546
20547    @Override
20548    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20549        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
20550
20551        DumpState dumpState = new DumpState();
20552        boolean fullPreferred = false;
20553        boolean checkin = false;
20554
20555        String packageName = null;
20556        ArraySet<String> permissionNames = null;
20557
20558        int opti = 0;
20559        while (opti < args.length) {
20560            String opt = args[opti];
20561            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20562                break;
20563            }
20564            opti++;
20565
20566            if ("-a".equals(opt)) {
20567                // Right now we only know how to print all.
20568            } else if ("-h".equals(opt)) {
20569                pw.println("Package manager dump options:");
20570                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20571                pw.println("    --checkin: dump for a checkin");
20572                pw.println("    -f: print details of intent filters");
20573                pw.println("    -h: print this help");
20574                pw.println("  cmd may be one of:");
20575                pw.println("    l[ibraries]: list known shared libraries");
20576                pw.println("    f[eatures]: list device features");
20577                pw.println("    k[eysets]: print known keysets");
20578                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20579                pw.println("    perm[issions]: dump permissions");
20580                pw.println("    permission [name ...]: dump declaration and use of given permission");
20581                pw.println("    pref[erred]: print preferred package settings");
20582                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20583                pw.println("    prov[iders]: dump content providers");
20584                pw.println("    p[ackages]: dump installed packages");
20585                pw.println("    s[hared-users]: dump shared user IDs");
20586                pw.println("    m[essages]: print collected runtime messages");
20587                pw.println("    v[erifiers]: print package verifier info");
20588                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20589                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20590                pw.println("    version: print database version info");
20591                pw.println("    write: write current settings now");
20592                pw.println("    installs: details about install sessions");
20593                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20594                pw.println("    dexopt: dump dexopt state");
20595                pw.println("    compiler-stats: dump compiler statistics");
20596                pw.println("    enabled-overlays: dump list of enabled overlay packages");
20597                pw.println("    service-permissions: dump permissions required by services");
20598                pw.println("    <package.name>: info about given package");
20599                return;
20600            } else if ("--checkin".equals(opt)) {
20601                checkin = true;
20602            } else if ("-f".equals(opt)) {
20603                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20604            } else if ("--proto".equals(opt)) {
20605                dumpProto(fd);
20606                return;
20607            } else {
20608                pw.println("Unknown argument: " + opt + "; use -h for help");
20609            }
20610        }
20611
20612        // Is the caller requesting to dump a particular piece of data?
20613        if (opti < args.length) {
20614            String cmd = args[opti];
20615            opti++;
20616            // Is this a package name?
20617            if ("android".equals(cmd) || cmd.contains(".")) {
20618                packageName = cmd;
20619                // When dumping a single package, we always dump all of its
20620                // filter information since the amount of data will be reasonable.
20621                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20622            } else if ("check-permission".equals(cmd)) {
20623                if (opti >= args.length) {
20624                    pw.println("Error: check-permission missing permission argument");
20625                    return;
20626                }
20627                String perm = args[opti];
20628                opti++;
20629                if (opti >= args.length) {
20630                    pw.println("Error: check-permission missing package argument");
20631                    return;
20632                }
20633
20634                String pkg = args[opti];
20635                opti++;
20636                int user = UserHandle.getUserId(Binder.getCallingUid());
20637                if (opti < args.length) {
20638                    try {
20639                        user = Integer.parseInt(args[opti]);
20640                    } catch (NumberFormatException e) {
20641                        pw.println("Error: check-permission user argument is not a number: "
20642                                + args[opti]);
20643                        return;
20644                    }
20645                }
20646
20647                // Normalize package name to handle renamed packages and static libs
20648                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20649
20650                pw.println(checkPermission(perm, pkg, user));
20651                return;
20652            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20653                dumpState.setDump(DumpState.DUMP_LIBS);
20654            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20655                dumpState.setDump(DumpState.DUMP_FEATURES);
20656            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20657                if (opti >= args.length) {
20658                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20659                            | DumpState.DUMP_SERVICE_RESOLVERS
20660                            | DumpState.DUMP_RECEIVER_RESOLVERS
20661                            | DumpState.DUMP_CONTENT_RESOLVERS);
20662                } else {
20663                    while (opti < args.length) {
20664                        String name = args[opti];
20665                        if ("a".equals(name) || "activity".equals(name)) {
20666                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20667                        } else if ("s".equals(name) || "service".equals(name)) {
20668                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20669                        } else if ("r".equals(name) || "receiver".equals(name)) {
20670                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20671                        } else if ("c".equals(name) || "content".equals(name)) {
20672                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20673                        } else {
20674                            pw.println("Error: unknown resolver table type: " + name);
20675                            return;
20676                        }
20677                        opti++;
20678                    }
20679                }
20680            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20681                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20682            } else if ("permission".equals(cmd)) {
20683                if (opti >= args.length) {
20684                    pw.println("Error: permission requires permission name");
20685                    return;
20686                }
20687                permissionNames = new ArraySet<>();
20688                while (opti < args.length) {
20689                    permissionNames.add(args[opti]);
20690                    opti++;
20691                }
20692                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20693                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20694            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20695                dumpState.setDump(DumpState.DUMP_PREFERRED);
20696            } else if ("preferred-xml".equals(cmd)) {
20697                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20698                if (opti < args.length && "--full".equals(args[opti])) {
20699                    fullPreferred = true;
20700                    opti++;
20701                }
20702            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20703                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20704            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20705                dumpState.setDump(DumpState.DUMP_PACKAGES);
20706            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20707                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20708            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20709                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20710            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20711                dumpState.setDump(DumpState.DUMP_MESSAGES);
20712            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20713                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20714            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20715                    || "intent-filter-verifiers".equals(cmd)) {
20716                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20717            } else if ("version".equals(cmd)) {
20718                dumpState.setDump(DumpState.DUMP_VERSION);
20719            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20720                dumpState.setDump(DumpState.DUMP_KEYSETS);
20721            } else if ("installs".equals(cmd)) {
20722                dumpState.setDump(DumpState.DUMP_INSTALLS);
20723            } else if ("frozen".equals(cmd)) {
20724                dumpState.setDump(DumpState.DUMP_FROZEN);
20725            } else if ("volumes".equals(cmd)) {
20726                dumpState.setDump(DumpState.DUMP_VOLUMES);
20727            } else if ("dexopt".equals(cmd)) {
20728                dumpState.setDump(DumpState.DUMP_DEXOPT);
20729            } else if ("compiler-stats".equals(cmd)) {
20730                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
20731            } else if ("changes".equals(cmd)) {
20732                dumpState.setDump(DumpState.DUMP_CHANGES);
20733            } else if ("service-permissions".equals(cmd)) {
20734                dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS);
20735            } else if ("write".equals(cmd)) {
20736                synchronized (mPackages) {
20737                    mSettings.writeLPr();
20738                    pw.println("Settings written.");
20739                    return;
20740                }
20741            }
20742        }
20743
20744        if (checkin) {
20745            pw.println("vers,1");
20746        }
20747
20748        // reader
20749        synchronized (mPackages) {
20750            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
20751                if (!checkin) {
20752                    if (dumpState.onTitlePrinted())
20753                        pw.println();
20754                    pw.println("Database versions:");
20755                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
20756                }
20757            }
20758
20759            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
20760                if (!checkin) {
20761                    if (dumpState.onTitlePrinted())
20762                        pw.println();
20763                    pw.println("Verifiers:");
20764                    pw.print("  Required: ");
20765                    pw.print(mRequiredVerifierPackage);
20766                    pw.print(" (uid=");
20767                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20768                            UserHandle.USER_SYSTEM));
20769                    pw.println(")");
20770                } else if (mRequiredVerifierPackage != null) {
20771                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
20772                    pw.print(",");
20773                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20774                            UserHandle.USER_SYSTEM));
20775                }
20776            }
20777
20778            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
20779                    packageName == null) {
20780                if (mIntentFilterVerifierComponent != null) {
20781                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20782                    if (!checkin) {
20783                        if (dumpState.onTitlePrinted())
20784                            pw.println();
20785                        pw.println("Intent Filter Verifier:");
20786                        pw.print("  Using: ");
20787                        pw.print(verifierPackageName);
20788                        pw.print(" (uid=");
20789                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20790                                UserHandle.USER_SYSTEM));
20791                        pw.println(")");
20792                    } else if (verifierPackageName != null) {
20793                        pw.print("ifv,"); pw.print(verifierPackageName);
20794                        pw.print(",");
20795                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20796                                UserHandle.USER_SYSTEM));
20797                    }
20798                } else {
20799                    pw.println();
20800                    pw.println("No Intent Filter Verifier available!");
20801                }
20802            }
20803
20804            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
20805                boolean printedHeader = false;
20806                final Iterator<String> it = mSharedLibraries.keySet().iterator();
20807                while (it.hasNext()) {
20808                    String libName = it.next();
20809                    LongSparseArray<SharedLibraryEntry> versionedLib
20810                            = mSharedLibraries.get(libName);
20811                    if (versionedLib == null) {
20812                        continue;
20813                    }
20814                    final int versionCount = versionedLib.size();
20815                    for (int i = 0; i < versionCount; i++) {
20816                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
20817                        if (!checkin) {
20818                            if (!printedHeader) {
20819                                if (dumpState.onTitlePrinted())
20820                                    pw.println();
20821                                pw.println("Libraries:");
20822                                printedHeader = true;
20823                            }
20824                            pw.print("  ");
20825                        } else {
20826                            pw.print("lib,");
20827                        }
20828                        pw.print(libEntry.info.getName());
20829                        if (libEntry.info.isStatic()) {
20830                            pw.print(" version=" + libEntry.info.getLongVersion());
20831                        }
20832                        if (!checkin) {
20833                            pw.print(" -> ");
20834                        }
20835                        if (libEntry.path != null) {
20836                            pw.print(" (jar) ");
20837                            pw.print(libEntry.path);
20838                        } else {
20839                            pw.print(" (apk) ");
20840                            pw.print(libEntry.apk);
20841                        }
20842                        pw.println();
20843                    }
20844                }
20845            }
20846
20847            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
20848                if (dumpState.onTitlePrinted())
20849                    pw.println();
20850                if (!checkin) {
20851                    pw.println("Features:");
20852                }
20853
20854                synchronized (mAvailableFeatures) {
20855                    for (FeatureInfo feat : mAvailableFeatures.values()) {
20856                        if (checkin) {
20857                            pw.print("feat,");
20858                            pw.print(feat.name);
20859                            pw.print(",");
20860                            pw.println(feat.version);
20861                        } else {
20862                            pw.print("  ");
20863                            pw.print(feat.name);
20864                            if (feat.version > 0) {
20865                                pw.print(" version=");
20866                                pw.print(feat.version);
20867                            }
20868                            pw.println();
20869                        }
20870                    }
20871                }
20872            }
20873
20874            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
20875                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
20876                        : "Activity Resolver Table:", "  ", packageName,
20877                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20878                    dumpState.setTitlePrinted(true);
20879                }
20880            }
20881            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
20882                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
20883                        : "Receiver Resolver Table:", "  ", packageName,
20884                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20885                    dumpState.setTitlePrinted(true);
20886                }
20887            }
20888            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
20889                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
20890                        : "Service Resolver Table:", "  ", packageName,
20891                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20892                    dumpState.setTitlePrinted(true);
20893                }
20894            }
20895            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
20896                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
20897                        : "Provider Resolver Table:", "  ", packageName,
20898                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20899                    dumpState.setTitlePrinted(true);
20900                }
20901            }
20902
20903            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
20904                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20905                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20906                    int user = mSettings.mPreferredActivities.keyAt(i);
20907                    if (pir.dump(pw,
20908                            dumpState.getTitlePrinted()
20909                                ? "\nPreferred Activities User " + user + ":"
20910                                : "Preferred Activities User " + user + ":", "  ",
20911                            packageName, true, false)) {
20912                        dumpState.setTitlePrinted(true);
20913                    }
20914                }
20915            }
20916
20917            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
20918                pw.flush();
20919                FileOutputStream fout = new FileOutputStream(fd);
20920                BufferedOutputStream str = new BufferedOutputStream(fout);
20921                XmlSerializer serializer = new FastXmlSerializer();
20922                try {
20923                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
20924                    serializer.startDocument(null, true);
20925                    serializer.setFeature(
20926                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
20927                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
20928                    serializer.endDocument();
20929                    serializer.flush();
20930                } catch (IllegalArgumentException e) {
20931                    pw.println("Failed writing: " + e);
20932                } catch (IllegalStateException e) {
20933                    pw.println("Failed writing: " + e);
20934                } catch (IOException e) {
20935                    pw.println("Failed writing: " + e);
20936                }
20937            }
20938
20939            if (!checkin
20940                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
20941                    && packageName == null) {
20942                pw.println();
20943                int count = mSettings.mPackages.size();
20944                if (count == 0) {
20945                    pw.println("No applications!");
20946                    pw.println();
20947                } else {
20948                    final String prefix = "  ";
20949                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
20950                    if (allPackageSettings.size() == 0) {
20951                        pw.println("No domain preferred apps!");
20952                        pw.println();
20953                    } else {
20954                        pw.println("App verification status:");
20955                        pw.println();
20956                        count = 0;
20957                        for (PackageSetting ps : allPackageSettings) {
20958                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
20959                            if (ivi == null || ivi.getPackageName() == null) continue;
20960                            pw.println(prefix + "Package: " + ivi.getPackageName());
20961                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
20962                            pw.println(prefix + "Status:  " + ivi.getStatusString());
20963                            pw.println();
20964                            count++;
20965                        }
20966                        if (count == 0) {
20967                            pw.println(prefix + "No app verification established.");
20968                            pw.println();
20969                        }
20970                        for (int userId : sUserManager.getUserIds()) {
20971                            pw.println("App linkages for user " + userId + ":");
20972                            pw.println();
20973                            count = 0;
20974                            for (PackageSetting ps : allPackageSettings) {
20975                                final long status = ps.getDomainVerificationStatusForUser(userId);
20976                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
20977                                        && !DEBUG_DOMAIN_VERIFICATION) {
20978                                    continue;
20979                                }
20980                                pw.println(prefix + "Package: " + ps.name);
20981                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
20982                                String statusStr = IntentFilterVerificationInfo.
20983                                        getStatusStringFromValue(status);
20984                                pw.println(prefix + "Status:  " + statusStr);
20985                                pw.println();
20986                                count++;
20987                            }
20988                            if (count == 0) {
20989                                pw.println(prefix + "No configured app linkages.");
20990                                pw.println();
20991                            }
20992                        }
20993                    }
20994                }
20995            }
20996
20997            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
20998                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
20999            }
21000
21001            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21002                boolean printedSomething = false;
21003                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21004                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21005                        continue;
21006                    }
21007                    if (!printedSomething) {
21008                        if (dumpState.onTitlePrinted())
21009                            pw.println();
21010                        pw.println("Registered ContentProviders:");
21011                        printedSomething = true;
21012                    }
21013                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21014                    pw.print("    "); pw.println(p.toString());
21015                }
21016                printedSomething = false;
21017                for (Map.Entry<String, PackageParser.Provider> entry :
21018                        mProvidersByAuthority.entrySet()) {
21019                    PackageParser.Provider p = entry.getValue();
21020                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21021                        continue;
21022                    }
21023                    if (!printedSomething) {
21024                        if (dumpState.onTitlePrinted())
21025                            pw.println();
21026                        pw.println("ContentProvider Authorities:");
21027                        printedSomething = true;
21028                    }
21029                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21030                    pw.print("    "); pw.println(p.toString());
21031                    if (p.info != null && p.info.applicationInfo != null) {
21032                        final String appInfo = p.info.applicationInfo.toString();
21033                        pw.print("      applicationInfo="); pw.println(appInfo);
21034                    }
21035                }
21036            }
21037
21038            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21039                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21040            }
21041
21042            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21043                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21044            }
21045
21046            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21047                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21048            }
21049
21050            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21051                if (dumpState.onTitlePrinted()) pw.println();
21052                pw.println("Package Changes:");
21053                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21054                final int K = mChangedPackages.size();
21055                for (int i = 0; i < K; i++) {
21056                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21057                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21058                    final int N = changes.size();
21059                    if (N == 0) {
21060                        pw.print("    "); pw.println("No packages changed");
21061                    } else {
21062                        for (int j = 0; j < N; j++) {
21063                            final String pkgName = changes.valueAt(j);
21064                            final int sequenceNumber = changes.keyAt(j);
21065                            pw.print("    ");
21066                            pw.print("seq=");
21067                            pw.print(sequenceNumber);
21068                            pw.print(", package=");
21069                            pw.println(pkgName);
21070                        }
21071                    }
21072                }
21073            }
21074
21075            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21076                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21077            }
21078
21079            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21080                // XXX should handle packageName != null by dumping only install data that
21081                // the given package is involved with.
21082                if (dumpState.onTitlePrinted()) pw.println();
21083
21084                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21085                ipw.println();
21086                ipw.println("Frozen packages:");
21087                ipw.increaseIndent();
21088                if (mFrozenPackages.size() == 0) {
21089                    ipw.println("(none)");
21090                } else {
21091                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21092                        ipw.println(mFrozenPackages.valueAt(i));
21093                    }
21094                }
21095                ipw.decreaseIndent();
21096            }
21097
21098            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
21099                if (dumpState.onTitlePrinted()) pw.println();
21100
21101                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21102                ipw.println();
21103                ipw.println("Loaded volumes:");
21104                ipw.increaseIndent();
21105                if (mLoadedVolumes.size() == 0) {
21106                    ipw.println("(none)");
21107                } else {
21108                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
21109                        ipw.println(mLoadedVolumes.valueAt(i));
21110                    }
21111                }
21112                ipw.decreaseIndent();
21113            }
21114
21115            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS)
21116                    && packageName == null) {
21117                if (dumpState.onTitlePrinted()) pw.println();
21118                pw.println("Service permissions:");
21119
21120                final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator();
21121                while (filterIterator.hasNext()) {
21122                    final ServiceIntentInfo info = filterIterator.next();
21123                    final ServiceInfo serviceInfo = info.service.info;
21124                    final String permission = serviceInfo.permission;
21125                    if (permission != null) {
21126                        pw.print("    ");
21127                        pw.print(serviceInfo.getComponentName().flattenToShortString());
21128                        pw.print(": ");
21129                        pw.println(permission);
21130                    }
21131                }
21132            }
21133
21134            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21135                if (dumpState.onTitlePrinted()) pw.println();
21136                dumpDexoptStateLPr(pw, packageName);
21137            }
21138
21139            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21140                if (dumpState.onTitlePrinted()) pw.println();
21141                dumpCompilerStatsLPr(pw, packageName);
21142            }
21143
21144            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21145                if (dumpState.onTitlePrinted()) pw.println();
21146                mSettings.dumpReadMessagesLPr(pw, dumpState);
21147
21148                pw.println();
21149                pw.println("Package warning messages:");
21150                dumpCriticalInfo(pw, null);
21151            }
21152
21153            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21154                dumpCriticalInfo(pw, "msg,");
21155            }
21156        }
21157
21158        // PackageInstaller should be called outside of mPackages lock
21159        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21160            // XXX should handle packageName != null by dumping only install data that
21161            // the given package is involved with.
21162            if (dumpState.onTitlePrinted()) pw.println();
21163            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21164        }
21165    }
21166
21167    private void dumpProto(FileDescriptor fd) {
21168        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21169
21170        synchronized (mPackages) {
21171            final long requiredVerifierPackageToken =
21172                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21173            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21174            proto.write(
21175                    PackageServiceDumpProto.PackageShortProto.UID,
21176                    getPackageUid(
21177                            mRequiredVerifierPackage,
21178                            MATCH_DEBUG_TRIAGED_MISSING,
21179                            UserHandle.USER_SYSTEM));
21180            proto.end(requiredVerifierPackageToken);
21181
21182            if (mIntentFilterVerifierComponent != null) {
21183                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21184                final long verifierPackageToken =
21185                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21186                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21187                proto.write(
21188                        PackageServiceDumpProto.PackageShortProto.UID,
21189                        getPackageUid(
21190                                verifierPackageName,
21191                                MATCH_DEBUG_TRIAGED_MISSING,
21192                                UserHandle.USER_SYSTEM));
21193                proto.end(verifierPackageToken);
21194            }
21195
21196            dumpSharedLibrariesProto(proto);
21197            dumpFeaturesProto(proto);
21198            mSettings.dumpPackagesProto(proto);
21199            mSettings.dumpSharedUsersProto(proto);
21200            dumpCriticalInfo(proto);
21201        }
21202        proto.flush();
21203    }
21204
21205    private void dumpFeaturesProto(ProtoOutputStream proto) {
21206        synchronized (mAvailableFeatures) {
21207            final int count = mAvailableFeatures.size();
21208            for (int i = 0; i < count; i++) {
21209                mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
21210            }
21211        }
21212    }
21213
21214    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21215        final int count = mSharedLibraries.size();
21216        for (int i = 0; i < count; i++) {
21217            final String libName = mSharedLibraries.keyAt(i);
21218            LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21219            if (versionedLib == null) {
21220                continue;
21221            }
21222            final int versionCount = versionedLib.size();
21223            for (int j = 0; j < versionCount; j++) {
21224                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21225                final long sharedLibraryToken =
21226                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21227                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21228                final boolean isJar = (libEntry.path != null);
21229                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21230                if (isJar) {
21231                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21232                } else {
21233                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21234                }
21235                proto.end(sharedLibraryToken);
21236            }
21237        }
21238    }
21239
21240    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21241        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21242        ipw.println();
21243        ipw.println("Dexopt state:");
21244        ipw.increaseIndent();
21245        Collection<PackageParser.Package> packages = null;
21246        if (packageName != null) {
21247            PackageParser.Package targetPackage = mPackages.get(packageName);
21248            if (targetPackage != null) {
21249                packages = Collections.singletonList(targetPackage);
21250            } else {
21251                ipw.println("Unable to find package: " + packageName);
21252                return;
21253            }
21254        } else {
21255            packages = mPackages.values();
21256        }
21257
21258        for (PackageParser.Package pkg : packages) {
21259            ipw.println("[" + pkg.packageName + "]");
21260            ipw.increaseIndent();
21261            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
21262                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
21263            ipw.decreaseIndent();
21264        }
21265    }
21266
21267    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21268        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21269        ipw.println();
21270        ipw.println("Compiler stats:");
21271        ipw.increaseIndent();
21272        Collection<PackageParser.Package> packages = null;
21273        if (packageName != null) {
21274            PackageParser.Package targetPackage = mPackages.get(packageName);
21275            if (targetPackage != null) {
21276                packages = Collections.singletonList(targetPackage);
21277            } else {
21278                ipw.println("Unable to find package: " + packageName);
21279                return;
21280            }
21281        } else {
21282            packages = mPackages.values();
21283        }
21284
21285        for (PackageParser.Package pkg : packages) {
21286            ipw.println("[" + pkg.packageName + "]");
21287            ipw.increaseIndent();
21288
21289            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21290            if (stats == null) {
21291                ipw.println("(No recorded stats)");
21292            } else {
21293                stats.dump(ipw);
21294            }
21295            ipw.decreaseIndent();
21296        }
21297    }
21298
21299    private String dumpDomainString(String packageName) {
21300        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21301                .getList();
21302        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21303
21304        ArraySet<String> result = new ArraySet<>();
21305        if (iviList.size() > 0) {
21306            for (IntentFilterVerificationInfo ivi : iviList) {
21307                for (String host : ivi.getDomains()) {
21308                    result.add(host);
21309                }
21310            }
21311        }
21312        if (filters != null && filters.size() > 0) {
21313            for (IntentFilter filter : filters) {
21314                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21315                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21316                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21317                    result.addAll(filter.getHostsList());
21318                }
21319            }
21320        }
21321
21322        StringBuilder sb = new StringBuilder(result.size() * 16);
21323        for (String domain : result) {
21324            if (sb.length() > 0) sb.append(" ");
21325            sb.append(domain);
21326        }
21327        return sb.toString();
21328    }
21329
21330    // ------- apps on sdcard specific code -------
21331    static final boolean DEBUG_SD_INSTALL = false;
21332
21333    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21334
21335    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21336
21337    private boolean mMediaMounted = false;
21338
21339    static String getEncryptKey() {
21340        try {
21341            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21342                    SD_ENCRYPTION_KEYSTORE_NAME);
21343            if (sdEncKey == null) {
21344                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21345                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21346                if (sdEncKey == null) {
21347                    Slog.e(TAG, "Failed to create encryption keys");
21348                    return null;
21349                }
21350            }
21351            return sdEncKey;
21352        } catch (NoSuchAlgorithmException nsae) {
21353            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21354            return null;
21355        } catch (IOException ioe) {
21356            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21357            return null;
21358        }
21359    }
21360
21361    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21362            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21363        final int size = infos.size();
21364        final String[] packageNames = new String[size];
21365        final int[] packageUids = new int[size];
21366        for (int i = 0; i < size; i++) {
21367            final ApplicationInfo info = infos.get(i);
21368            packageNames[i] = info.packageName;
21369            packageUids[i] = info.uid;
21370        }
21371        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21372                finishedReceiver);
21373    }
21374
21375    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21376            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21377        sendResourcesChangedBroadcast(mediaStatus, replacing,
21378                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21379    }
21380
21381    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21382            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21383        int size = pkgList.length;
21384        if (size > 0) {
21385            // Send broadcasts here
21386            Bundle extras = new Bundle();
21387            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21388            if (uidArr != null) {
21389                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21390            }
21391            if (replacing) {
21392                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21393            }
21394            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21395                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21396            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null);
21397        }
21398    }
21399
21400    private void loadPrivatePackages(final VolumeInfo vol) {
21401        mHandler.post(new Runnable() {
21402            @Override
21403            public void run() {
21404                loadPrivatePackagesInner(vol);
21405            }
21406        });
21407    }
21408
21409    private void loadPrivatePackagesInner(VolumeInfo vol) {
21410        final String volumeUuid = vol.fsUuid;
21411        if (TextUtils.isEmpty(volumeUuid)) {
21412            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21413            return;
21414        }
21415
21416        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21417        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21418        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21419
21420        final VersionInfo ver;
21421        final List<PackageSetting> packages;
21422        synchronized (mPackages) {
21423            ver = mSettings.findOrCreateVersion(volumeUuid);
21424            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21425        }
21426
21427        for (PackageSetting ps : packages) {
21428            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21429            synchronized (mInstallLock) {
21430                final PackageParser.Package pkg;
21431                try {
21432                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21433                    loaded.add(pkg.applicationInfo);
21434
21435                } catch (PackageManagerException e) {
21436                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21437                }
21438
21439                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21440                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21441                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21442                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21443                }
21444            }
21445        }
21446
21447        // Reconcile app data for all started/unlocked users
21448        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21449        final UserManager um = mContext.getSystemService(UserManager.class);
21450        UserManagerInternal umInternal = getUserManagerInternal();
21451        for (UserInfo user : um.getUsers()) {
21452            final int flags;
21453            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21454                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21455            } else if (umInternal.isUserRunning(user.id)) {
21456                flags = StorageManager.FLAG_STORAGE_DE;
21457            } else {
21458                continue;
21459            }
21460
21461            try {
21462                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21463                synchronized (mInstallLock) {
21464                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21465                }
21466            } catch (IllegalStateException e) {
21467                // Device was probably ejected, and we'll process that event momentarily
21468                Slog.w(TAG, "Failed to prepare storage: " + e);
21469            }
21470        }
21471
21472        synchronized (mPackages) {
21473            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
21474            if (sdkUpdated) {
21475                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21476                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21477            }
21478            mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(),
21479                    mPermissionCallback);
21480
21481            // Yay, everything is now upgraded
21482            ver.forceCurrent();
21483
21484            mSettings.writeLPr();
21485        }
21486
21487        for (PackageFreezer freezer : freezers) {
21488            freezer.close();
21489        }
21490
21491        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21492        sendResourcesChangedBroadcast(true, false, loaded, null);
21493        mLoadedVolumes.add(vol.getId());
21494    }
21495
21496    private void unloadPrivatePackages(final VolumeInfo vol) {
21497        mHandler.post(new Runnable() {
21498            @Override
21499            public void run() {
21500                unloadPrivatePackagesInner(vol);
21501            }
21502        });
21503    }
21504
21505    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21506        final String volumeUuid = vol.fsUuid;
21507        if (TextUtils.isEmpty(volumeUuid)) {
21508            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21509            return;
21510        }
21511
21512        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21513        synchronized (mInstallLock) {
21514        synchronized (mPackages) {
21515            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21516            for (PackageSetting ps : packages) {
21517                if (ps.pkg == null) continue;
21518
21519                final ApplicationInfo info = ps.pkg.applicationInfo;
21520                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21521                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
21522
21523                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21524                        "unloadPrivatePackagesInner")) {
21525                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21526                            false, null)) {
21527                        unloaded.add(info);
21528                    } else {
21529                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21530                    }
21531                }
21532
21533                // Try very hard to release any references to this package
21534                // so we don't risk the system server being killed due to
21535                // open FDs
21536                AttributeCache.instance().removePackage(ps.name);
21537            }
21538
21539            mSettings.writeLPr();
21540        }
21541        }
21542
21543        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21544        sendResourcesChangedBroadcast(false, false, unloaded, null);
21545        mLoadedVolumes.remove(vol.getId());
21546
21547        // Try very hard to release any references to this path so we don't risk
21548        // the system server being killed due to open FDs
21549        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21550
21551        for (int i = 0; i < 3; i++) {
21552            System.gc();
21553            System.runFinalization();
21554        }
21555    }
21556
21557    private void assertPackageKnown(String volumeUuid, String packageName)
21558            throws PackageManagerException {
21559        synchronized (mPackages) {
21560            // Normalize package name to handle renamed packages
21561            packageName = normalizePackageNameLPr(packageName);
21562
21563            final PackageSetting ps = mSettings.mPackages.get(packageName);
21564            if (ps == null) {
21565                throw new PackageManagerException("Package " + packageName + " is unknown");
21566            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21567                throw new PackageManagerException(
21568                        "Package " + packageName + " found on unknown volume " + volumeUuid
21569                                + "; expected volume " + ps.volumeUuid);
21570            }
21571        }
21572    }
21573
21574    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21575            throws PackageManagerException {
21576        synchronized (mPackages) {
21577            // Normalize package name to handle renamed packages
21578            packageName = normalizePackageNameLPr(packageName);
21579
21580            final PackageSetting ps = mSettings.mPackages.get(packageName);
21581            if (ps == null) {
21582                throw new PackageManagerException("Package " + packageName + " is unknown");
21583            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21584                throw new PackageManagerException(
21585                        "Package " + packageName + " found on unknown volume " + volumeUuid
21586                                + "; expected volume " + ps.volumeUuid);
21587            } else if (!ps.getInstalled(userId)) {
21588                throw new PackageManagerException(
21589                        "Package " + packageName + " not installed for user " + userId);
21590            }
21591        }
21592    }
21593
21594    private List<String> collectAbsoluteCodePaths() {
21595        synchronized (mPackages) {
21596            List<String> codePaths = new ArrayList<>();
21597            final int packageCount = mSettings.mPackages.size();
21598            for (int i = 0; i < packageCount; i++) {
21599                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21600                codePaths.add(ps.codePath.getAbsolutePath());
21601            }
21602            return codePaths;
21603        }
21604    }
21605
21606    /**
21607     * Examine all apps present on given mounted volume, and destroy apps that
21608     * aren't expected, either due to uninstallation or reinstallation on
21609     * another volume.
21610     */
21611    private void reconcileApps(String volumeUuid) {
21612        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21613        List<File> filesToDelete = null;
21614
21615        final File[] files = FileUtils.listFilesOrEmpty(
21616                Environment.getDataAppDirectory(volumeUuid));
21617        for (File file : files) {
21618            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21619                    && !PackageInstallerService.isStageName(file.getName());
21620            if (!isPackage) {
21621                // Ignore entries which are not packages
21622                continue;
21623            }
21624
21625            String absolutePath = file.getAbsolutePath();
21626
21627            boolean pathValid = false;
21628            final int absoluteCodePathCount = absoluteCodePaths.size();
21629            for (int i = 0; i < absoluteCodePathCount; i++) {
21630                String absoluteCodePath = absoluteCodePaths.get(i);
21631                if (absolutePath.startsWith(absoluteCodePath)) {
21632                    pathValid = true;
21633                    break;
21634                }
21635            }
21636
21637            if (!pathValid) {
21638                if (filesToDelete == null) {
21639                    filesToDelete = new ArrayList<>();
21640                }
21641                filesToDelete.add(file);
21642            }
21643        }
21644
21645        if (filesToDelete != null) {
21646            final int fileToDeleteCount = filesToDelete.size();
21647            for (int i = 0; i < fileToDeleteCount; i++) {
21648                File fileToDelete = filesToDelete.get(i);
21649                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
21650                synchronized (mInstallLock) {
21651                    removeCodePathLI(fileToDelete);
21652                }
21653            }
21654        }
21655    }
21656
21657    /**
21658     * Reconcile all app data for the given user.
21659     * <p>
21660     * Verifies that directories exist and that ownership and labeling is
21661     * correct for all installed apps on all mounted volumes.
21662     */
21663    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
21664        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21665        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
21666            final String volumeUuid = vol.getFsUuid();
21667            synchronized (mInstallLock) {
21668                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
21669            }
21670        }
21671    }
21672
21673    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21674            boolean migrateAppData) {
21675        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
21676    }
21677
21678    /**
21679     * Reconcile all app data on given mounted volume.
21680     * <p>
21681     * Destroys app data that isn't expected, either due to uninstallation or
21682     * reinstallation on another volume.
21683     * <p>
21684     * Verifies that directories exist and that ownership and labeling is
21685     * correct for all installed apps.
21686     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
21687     */
21688    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21689            boolean migrateAppData, boolean onlyCoreApps) {
21690        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
21691                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
21692        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
21693
21694        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
21695        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
21696
21697        // First look for stale data that doesn't belong, and check if things
21698        // have changed since we did our last restorecon
21699        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21700            if (StorageManager.isFileEncryptedNativeOrEmulated()
21701                    && !StorageManager.isUserKeyUnlocked(userId)) {
21702                throw new RuntimeException(
21703                        "Yikes, someone asked us to reconcile CE storage while " + userId
21704                                + " was still locked; this would have caused massive data loss!");
21705            }
21706
21707            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
21708            for (File file : files) {
21709                final String packageName = file.getName();
21710                try {
21711                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21712                } catch (PackageManagerException e) {
21713                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21714                    try {
21715                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21716                                StorageManager.FLAG_STORAGE_CE, 0);
21717                    } catch (InstallerException e2) {
21718                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21719                    }
21720                }
21721            }
21722        }
21723        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
21724            final File[] files = FileUtils.listFilesOrEmpty(deDir);
21725            for (File file : files) {
21726                final String packageName = file.getName();
21727                try {
21728                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21729                } catch (PackageManagerException e) {
21730                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21731                    try {
21732                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21733                                StorageManager.FLAG_STORAGE_DE, 0);
21734                    } catch (InstallerException e2) {
21735                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21736                    }
21737                }
21738            }
21739        }
21740
21741        // Ensure that data directories are ready to roll for all packages
21742        // installed for this volume and user
21743        final List<PackageSetting> packages;
21744        synchronized (mPackages) {
21745            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21746        }
21747        int preparedCount = 0;
21748        for (PackageSetting ps : packages) {
21749            final String packageName = ps.name;
21750            if (ps.pkg == null) {
21751                Slog.w(TAG, "Odd, missing scanned package " + packageName);
21752                // TODO: might be due to legacy ASEC apps; we should circle back
21753                // and reconcile again once they're scanned
21754                continue;
21755            }
21756            // Skip non-core apps if requested
21757            if (onlyCoreApps && !ps.pkg.coreApp) {
21758                result.add(packageName);
21759                continue;
21760            }
21761
21762            if (ps.getInstalled(userId)) {
21763                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
21764                preparedCount++;
21765            }
21766        }
21767
21768        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
21769        return result;
21770    }
21771
21772    /**
21773     * Prepare app data for the given app just after it was installed or
21774     * upgraded. This method carefully only touches users that it's installed
21775     * for, and it forces a restorecon to handle any seinfo changes.
21776     * <p>
21777     * Verifies that directories exist and that ownership and labeling is
21778     * correct for all installed apps. If there is an ownership mismatch, it
21779     * will try recovering system apps by wiping data; third-party app data is
21780     * left intact.
21781     * <p>
21782     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
21783     */
21784    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
21785        final PackageSetting ps;
21786        synchronized (mPackages) {
21787            ps = mSettings.mPackages.get(pkg.packageName);
21788            mSettings.writeKernelMappingLPr(ps);
21789        }
21790
21791        final UserManager um = mContext.getSystemService(UserManager.class);
21792        UserManagerInternal umInternal = getUserManagerInternal();
21793        for (UserInfo user : um.getUsers()) {
21794            final int flags;
21795            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21796                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21797            } else if (umInternal.isUserRunning(user.id)) {
21798                flags = StorageManager.FLAG_STORAGE_DE;
21799            } else {
21800                continue;
21801            }
21802
21803            if (ps.getInstalled(user.id)) {
21804                // TODO: when user data is locked, mark that we're still dirty
21805                prepareAppDataLIF(pkg, user.id, flags);
21806            }
21807        }
21808    }
21809
21810    /**
21811     * Prepare app data for the given app.
21812     * <p>
21813     * Verifies that directories exist and that ownership and labeling is
21814     * correct for all installed apps. If there is an ownership mismatch, this
21815     * will try recovering system apps by wiping data; third-party app data is
21816     * left intact.
21817     */
21818    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
21819        if (pkg == null) {
21820            Slog.wtf(TAG, "Package was null!", new Throwable());
21821            return;
21822        }
21823        prepareAppDataLeafLIF(pkg, userId, flags);
21824        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21825        for (int i = 0; i < childCount; i++) {
21826            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
21827        }
21828    }
21829
21830    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
21831            boolean maybeMigrateAppData) {
21832        prepareAppDataLIF(pkg, userId, flags);
21833
21834        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
21835            // We may have just shuffled around app data directories, so
21836            // prepare them one more time
21837            prepareAppDataLIF(pkg, userId, flags);
21838        }
21839    }
21840
21841    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21842        if (DEBUG_APP_DATA) {
21843            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
21844                    + Integer.toHexString(flags));
21845        }
21846
21847        final String volumeUuid = pkg.volumeUuid;
21848        final String packageName = pkg.packageName;
21849        final ApplicationInfo app = pkg.applicationInfo;
21850        final int appId = UserHandle.getAppId(app.uid);
21851
21852        Preconditions.checkNotNull(app.seInfo);
21853
21854        long ceDataInode = -1;
21855        try {
21856            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21857                    appId, app.seInfo, app.targetSdkVersion);
21858        } catch (InstallerException e) {
21859            if (app.isSystemApp()) {
21860                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
21861                        + ", but trying to recover: " + e);
21862                destroyAppDataLeafLIF(pkg, userId, flags);
21863                try {
21864                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21865                            appId, app.seInfo, app.targetSdkVersion);
21866                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
21867                } catch (InstallerException e2) {
21868                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
21869                }
21870            } else {
21871                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
21872            }
21873        }
21874
21875        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
21876            // TODO: mark this structure as dirty so we persist it!
21877            synchronized (mPackages) {
21878                final PackageSetting ps = mSettings.mPackages.get(packageName);
21879                if (ps != null) {
21880                    ps.setCeDataInode(ceDataInode, userId);
21881                }
21882            }
21883        }
21884
21885        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21886    }
21887
21888    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
21889        if (pkg == null) {
21890            Slog.wtf(TAG, "Package was null!", new Throwable());
21891            return;
21892        }
21893        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21894        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21895        for (int i = 0; i < childCount; i++) {
21896            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
21897        }
21898    }
21899
21900    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21901        final String volumeUuid = pkg.volumeUuid;
21902        final String packageName = pkg.packageName;
21903        final ApplicationInfo app = pkg.applicationInfo;
21904
21905        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21906            // Create a native library symlink only if we have native libraries
21907            // and if the native libraries are 32 bit libraries. We do not provide
21908            // this symlink for 64 bit libraries.
21909            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
21910                final String nativeLibPath = app.nativeLibraryDir;
21911                try {
21912                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
21913                            nativeLibPath, userId);
21914                } catch (InstallerException e) {
21915                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
21916                }
21917            }
21918        }
21919    }
21920
21921    /**
21922     * For system apps on non-FBE devices, this method migrates any existing
21923     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
21924     * requested by the app.
21925     */
21926    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
21927        if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated()
21928                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
21929            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
21930                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
21931            try {
21932                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
21933                        storageTarget);
21934            } catch (InstallerException e) {
21935                logCriticalInfo(Log.WARN,
21936                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
21937            }
21938            return true;
21939        } else {
21940            return false;
21941        }
21942    }
21943
21944    public PackageFreezer freezePackage(String packageName, String killReason) {
21945        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
21946    }
21947
21948    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
21949        return new PackageFreezer(packageName, userId, killReason);
21950    }
21951
21952    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
21953            String killReason) {
21954        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
21955    }
21956
21957    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
21958            String killReason) {
21959        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
21960            return new PackageFreezer();
21961        } else {
21962            return freezePackage(packageName, userId, killReason);
21963        }
21964    }
21965
21966    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
21967            String killReason) {
21968        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
21969    }
21970
21971    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
21972            String killReason) {
21973        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
21974            return new PackageFreezer();
21975        } else {
21976            return freezePackage(packageName, userId, killReason);
21977        }
21978    }
21979
21980    /**
21981     * Class that freezes and kills the given package upon creation, and
21982     * unfreezes it upon closing. This is typically used when doing surgery on
21983     * app code/data to prevent the app from running while you're working.
21984     */
21985    private class PackageFreezer implements AutoCloseable {
21986        private final String mPackageName;
21987        private final PackageFreezer[] mChildren;
21988
21989        private final boolean mWeFroze;
21990
21991        private final AtomicBoolean mClosed = new AtomicBoolean();
21992        private final CloseGuard mCloseGuard = CloseGuard.get();
21993
21994        /**
21995         * Create and return a stub freezer that doesn't actually do anything,
21996         * typically used when someone requested
21997         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
21998         * {@link PackageManager#DELETE_DONT_KILL_APP}.
21999         */
22000        public PackageFreezer() {
22001            mPackageName = null;
22002            mChildren = null;
22003            mWeFroze = false;
22004            mCloseGuard.open("close");
22005        }
22006
22007        public PackageFreezer(String packageName, int userId, String killReason) {
22008            synchronized (mPackages) {
22009                mPackageName = packageName;
22010                mWeFroze = mFrozenPackages.add(mPackageName);
22011
22012                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22013                if (ps != null) {
22014                    killApplication(ps.name, ps.appId, userId, killReason);
22015                }
22016
22017                final PackageParser.Package p = mPackages.get(packageName);
22018                if (p != null && p.childPackages != null) {
22019                    final int N = p.childPackages.size();
22020                    mChildren = new PackageFreezer[N];
22021                    for (int i = 0; i < N; i++) {
22022                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22023                                userId, killReason);
22024                    }
22025                } else {
22026                    mChildren = null;
22027                }
22028            }
22029            mCloseGuard.open("close");
22030        }
22031
22032        @Override
22033        protected void finalize() throws Throwable {
22034            try {
22035                if (mCloseGuard != null) {
22036                    mCloseGuard.warnIfOpen();
22037                }
22038
22039                close();
22040            } finally {
22041                super.finalize();
22042            }
22043        }
22044
22045        @Override
22046        public void close() {
22047            mCloseGuard.close();
22048            if (mClosed.compareAndSet(false, true)) {
22049                synchronized (mPackages) {
22050                    if (mWeFroze) {
22051                        mFrozenPackages.remove(mPackageName);
22052                    }
22053
22054                    if (mChildren != null) {
22055                        for (PackageFreezer freezer : mChildren) {
22056                            freezer.close();
22057                        }
22058                    }
22059                }
22060            }
22061        }
22062    }
22063
22064    /**
22065     * Verify that given package is currently frozen.
22066     */
22067    private void checkPackageFrozen(String packageName) {
22068        synchronized (mPackages) {
22069            if (!mFrozenPackages.contains(packageName)) {
22070                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22071            }
22072        }
22073    }
22074
22075    @Override
22076    public int movePackage(final String packageName, final String volumeUuid) {
22077        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22078
22079        final int callingUid = Binder.getCallingUid();
22080        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
22081        final int moveId = mNextMoveId.getAndIncrement();
22082        mHandler.post(new Runnable() {
22083            @Override
22084            public void run() {
22085                try {
22086                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
22087                } catch (PackageManagerException e) {
22088                    Slog.w(TAG, "Failed to move " + packageName, e);
22089                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
22090                }
22091            }
22092        });
22093        return moveId;
22094    }
22095
22096    private void movePackageInternal(final String packageName, final String volumeUuid,
22097            final int moveId, final int callingUid, UserHandle user)
22098                    throws PackageManagerException {
22099        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22100        final PackageManager pm = mContext.getPackageManager();
22101
22102        final boolean currentAsec;
22103        final String currentVolumeUuid;
22104        final File codeFile;
22105        final String installerPackageName;
22106        final String packageAbiOverride;
22107        final int appId;
22108        final String seinfo;
22109        final String label;
22110        final int targetSdkVersion;
22111        final PackageFreezer freezer;
22112        final int[] installedUserIds;
22113
22114        // reader
22115        synchronized (mPackages) {
22116            final PackageParser.Package pkg = mPackages.get(packageName);
22117            final PackageSetting ps = mSettings.mPackages.get(packageName);
22118            if (pkg == null
22119                    || ps == null
22120                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
22121                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22122            }
22123            if (pkg.applicationInfo.isSystemApp()) {
22124                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22125                        "Cannot move system application");
22126            }
22127
22128            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22129            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22130                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22131            if (isInternalStorage && !allow3rdPartyOnInternal) {
22132                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22133                        "3rd party apps are not allowed on internal storage");
22134            }
22135
22136            if (pkg.applicationInfo.isExternalAsec()) {
22137                currentAsec = true;
22138                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22139            } else if (pkg.applicationInfo.isForwardLocked()) {
22140                currentAsec = true;
22141                currentVolumeUuid = "forward_locked";
22142            } else {
22143                currentAsec = false;
22144                currentVolumeUuid = ps.volumeUuid;
22145
22146                final File probe = new File(pkg.codePath);
22147                final File probeOat = new File(probe, "oat");
22148                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22149                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22150                            "Move only supported for modern cluster style installs");
22151                }
22152            }
22153
22154            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22155                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22156                        "Package already moved to " + volumeUuid);
22157            }
22158            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22159                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22160                        "Device admin cannot be moved");
22161            }
22162
22163            if (mFrozenPackages.contains(packageName)) {
22164                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22165                        "Failed to move already frozen package");
22166            }
22167
22168            codeFile = new File(pkg.codePath);
22169            installerPackageName = ps.installerPackageName;
22170            packageAbiOverride = ps.cpuAbiOverrideString;
22171            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22172            seinfo = pkg.applicationInfo.seInfo;
22173            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22174            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22175            freezer = freezePackage(packageName, "movePackageInternal");
22176            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22177        }
22178
22179        final Bundle extras = new Bundle();
22180        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22181        extras.putString(Intent.EXTRA_TITLE, label);
22182        mMoveCallbacks.notifyCreated(moveId, extras);
22183
22184        int installFlags;
22185        final boolean moveCompleteApp;
22186        final File measurePath;
22187
22188        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22189            installFlags = INSTALL_INTERNAL;
22190            moveCompleteApp = !currentAsec;
22191            measurePath = Environment.getDataAppDirectory(volumeUuid);
22192        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22193            installFlags = INSTALL_EXTERNAL;
22194            moveCompleteApp = false;
22195            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22196        } else {
22197            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22198            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22199                    || !volume.isMountedWritable()) {
22200                freezer.close();
22201                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22202                        "Move location not mounted private volume");
22203            }
22204
22205            Preconditions.checkState(!currentAsec);
22206
22207            installFlags = INSTALL_INTERNAL;
22208            moveCompleteApp = true;
22209            measurePath = Environment.getDataAppDirectory(volumeUuid);
22210        }
22211
22212        // If we're moving app data around, we need all the users unlocked
22213        if (moveCompleteApp) {
22214            for (int userId : installedUserIds) {
22215                if (StorageManager.isFileEncryptedNativeOrEmulated()
22216                        && !StorageManager.isUserKeyUnlocked(userId)) {
22217                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
22218                            "User " + userId + " must be unlocked");
22219                }
22220            }
22221        }
22222
22223        final PackageStats stats = new PackageStats(null, -1);
22224        synchronized (mInstaller) {
22225            for (int userId : installedUserIds) {
22226                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22227                    freezer.close();
22228                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22229                            "Failed to measure package size");
22230                }
22231            }
22232        }
22233
22234        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22235                + stats.dataSize);
22236
22237        final long startFreeBytes = measurePath.getUsableSpace();
22238        final long sizeBytes;
22239        if (moveCompleteApp) {
22240            sizeBytes = stats.codeSize + stats.dataSize;
22241        } else {
22242            sizeBytes = stats.codeSize;
22243        }
22244
22245        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22246            freezer.close();
22247            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22248                    "Not enough free space to move");
22249        }
22250
22251        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22252
22253        final CountDownLatch installedLatch = new CountDownLatch(1);
22254        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22255            @Override
22256            public void onUserActionRequired(Intent intent) throws RemoteException {
22257                throw new IllegalStateException();
22258            }
22259
22260            @Override
22261            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22262                    Bundle extras) throws RemoteException {
22263                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22264                        + PackageManager.installStatusToString(returnCode, msg));
22265
22266                installedLatch.countDown();
22267                freezer.close();
22268
22269                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22270                switch (status) {
22271                    case PackageInstaller.STATUS_SUCCESS:
22272                        mMoveCallbacks.notifyStatusChanged(moveId,
22273                                PackageManager.MOVE_SUCCEEDED);
22274                        break;
22275                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22276                        mMoveCallbacks.notifyStatusChanged(moveId,
22277                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22278                        break;
22279                    default:
22280                        mMoveCallbacks.notifyStatusChanged(moveId,
22281                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22282                        break;
22283                }
22284            }
22285        };
22286
22287        final MoveInfo move;
22288        if (moveCompleteApp) {
22289            // Kick off a thread to report progress estimates
22290            new Thread() {
22291                @Override
22292                public void run() {
22293                    while (true) {
22294                        try {
22295                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22296                                break;
22297                            }
22298                        } catch (InterruptedException ignored) {
22299                        }
22300
22301                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22302                        final int progress = 10 + (int) MathUtils.constrain(
22303                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22304                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22305                    }
22306                }
22307            }.start();
22308
22309            final String dataAppName = codeFile.getName();
22310            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22311                    dataAppName, appId, seinfo, targetSdkVersion);
22312        } else {
22313            move = null;
22314        }
22315
22316        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22317
22318        final Message msg = mHandler.obtainMessage(INIT_COPY);
22319        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22320        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22321                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22322                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
22323                PackageManager.INSTALL_REASON_UNKNOWN);
22324        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22325        msg.obj = params;
22326
22327        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22328                System.identityHashCode(msg.obj));
22329        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22330                System.identityHashCode(msg.obj));
22331
22332        mHandler.sendMessage(msg);
22333    }
22334
22335    @Override
22336    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22337        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22338
22339        final int realMoveId = mNextMoveId.getAndIncrement();
22340        final Bundle extras = new Bundle();
22341        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22342        mMoveCallbacks.notifyCreated(realMoveId, extras);
22343
22344        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22345            @Override
22346            public void onCreated(int moveId, Bundle extras) {
22347                // Ignored
22348            }
22349
22350            @Override
22351            public void onStatusChanged(int moveId, int status, long estMillis) {
22352                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22353            }
22354        };
22355
22356        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22357        storage.setPrimaryStorageUuid(volumeUuid, callback);
22358        return realMoveId;
22359    }
22360
22361    @Override
22362    public int getMoveStatus(int moveId) {
22363        mContext.enforceCallingOrSelfPermission(
22364                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22365        return mMoveCallbacks.mLastStatus.get(moveId);
22366    }
22367
22368    @Override
22369    public void registerMoveCallback(IPackageMoveObserver callback) {
22370        mContext.enforceCallingOrSelfPermission(
22371                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22372        mMoveCallbacks.register(callback);
22373    }
22374
22375    @Override
22376    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22377        mContext.enforceCallingOrSelfPermission(
22378                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22379        mMoveCallbacks.unregister(callback);
22380    }
22381
22382    @Override
22383    public boolean setInstallLocation(int loc) {
22384        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22385                null);
22386        if (getInstallLocation() == loc) {
22387            return true;
22388        }
22389        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22390                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22391            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22392                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22393            return true;
22394        }
22395        return false;
22396   }
22397
22398    @Override
22399    public int getInstallLocation() {
22400        // allow instant app access
22401        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22402                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22403                PackageHelper.APP_INSTALL_AUTO);
22404    }
22405
22406    /** Called by UserManagerService */
22407    void cleanUpUser(UserManagerService userManager, int userHandle) {
22408        synchronized (mPackages) {
22409            mDirtyUsers.remove(userHandle);
22410            mUserNeedsBadging.delete(userHandle);
22411            mSettings.removeUserLPw(userHandle);
22412            mPendingBroadcasts.remove(userHandle);
22413            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22414            removeUnusedPackagesLPw(userManager, userHandle);
22415        }
22416    }
22417
22418    /**
22419     * We're removing userHandle and would like to remove any downloaded packages
22420     * that are no longer in use by any other user.
22421     * @param userHandle the user being removed
22422     */
22423    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22424        final boolean DEBUG_CLEAN_APKS = false;
22425        int [] users = userManager.getUserIds();
22426        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22427        while (psit.hasNext()) {
22428            PackageSetting ps = psit.next();
22429            if (ps.pkg == null) {
22430                continue;
22431            }
22432            final String packageName = ps.pkg.packageName;
22433            // Skip over if system app
22434            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22435                continue;
22436            }
22437            if (DEBUG_CLEAN_APKS) {
22438                Slog.i(TAG, "Checking package " + packageName);
22439            }
22440            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22441            if (keep) {
22442                if (DEBUG_CLEAN_APKS) {
22443                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22444                }
22445            } else {
22446                for (int i = 0; i < users.length; i++) {
22447                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22448                        keep = true;
22449                        if (DEBUG_CLEAN_APKS) {
22450                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22451                                    + users[i]);
22452                        }
22453                        break;
22454                    }
22455                }
22456            }
22457            if (!keep) {
22458                if (DEBUG_CLEAN_APKS) {
22459                    Slog.i(TAG, "  Removing package " + packageName);
22460                }
22461                mHandler.post(new Runnable() {
22462                    public void run() {
22463                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22464                                userHandle, 0);
22465                    } //end run
22466                });
22467            }
22468        }
22469    }
22470
22471    /** Called by UserManagerService */
22472    void createNewUser(int userId, String[] disallowedPackages) {
22473        synchronized (mInstallLock) {
22474            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22475        }
22476        synchronized (mPackages) {
22477            scheduleWritePackageRestrictionsLocked(userId);
22478            scheduleWritePackageListLocked(userId);
22479            applyFactoryDefaultBrowserLPw(userId);
22480            primeDomainVerificationsLPw(userId);
22481        }
22482    }
22483
22484    void onNewUserCreated(final int userId) {
22485        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22486        synchronized(mPackages) {
22487            // If permission review for legacy apps is required, we represent
22488            // dagerous permissions for such apps as always granted runtime
22489            // permissions to keep per user flag state whether review is needed.
22490            // Hence, if a new user is added we have to propagate dangerous
22491            // permission grants for these legacy apps.
22492            if (mSettings.mPermissions.mPermissionReviewRequired) {
22493// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG
22494                mPermissionManager.updateAllPermissions(
22495                        StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(),
22496                        mPermissionCallback);
22497            }
22498        }
22499    }
22500
22501    @Override
22502    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22503        mContext.enforceCallingOrSelfPermission(
22504                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22505                "Only package verification agents can read the verifier device identity");
22506
22507        synchronized (mPackages) {
22508            return mSettings.getVerifierDeviceIdentityLPw();
22509        }
22510    }
22511
22512    @Override
22513    public void setPermissionEnforced(String permission, boolean enforced) {
22514        // TODO: Now that we no longer change GID for storage, this should to away.
22515        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22516                "setPermissionEnforced");
22517        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22518            synchronized (mPackages) {
22519                if (mSettings.mReadExternalStorageEnforced == null
22520                        || mSettings.mReadExternalStorageEnforced != enforced) {
22521                    mSettings.mReadExternalStorageEnforced =
22522                            enforced ? Boolean.TRUE : Boolean.FALSE;
22523                    mSettings.writeLPr();
22524                }
22525            }
22526            // kill any non-foreground processes so we restart them and
22527            // grant/revoke the GID.
22528            final IActivityManager am = ActivityManager.getService();
22529            if (am != null) {
22530                final long token = Binder.clearCallingIdentity();
22531                try {
22532                    am.killProcessesBelowForeground("setPermissionEnforcement");
22533                } catch (RemoteException e) {
22534                } finally {
22535                    Binder.restoreCallingIdentity(token);
22536                }
22537            }
22538        } else {
22539            throw new IllegalArgumentException("No selective enforcement for " + permission);
22540        }
22541    }
22542
22543    @Override
22544    @Deprecated
22545    public boolean isPermissionEnforced(String permission) {
22546        // allow instant applications
22547        return true;
22548    }
22549
22550    @Override
22551    public boolean isStorageLow() {
22552        // allow instant applications
22553        final long token = Binder.clearCallingIdentity();
22554        try {
22555            final DeviceStorageMonitorInternal
22556                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22557            if (dsm != null) {
22558                return dsm.isMemoryLow();
22559            } else {
22560                return false;
22561            }
22562        } finally {
22563            Binder.restoreCallingIdentity(token);
22564        }
22565    }
22566
22567    @Override
22568    public IPackageInstaller getPackageInstaller() {
22569        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
22570            return null;
22571        }
22572        return mInstallerService;
22573    }
22574
22575    @Override
22576    public IArtManager getArtManager() {
22577        return mArtManagerService;
22578    }
22579
22580    private boolean userNeedsBadging(int userId) {
22581        int index = mUserNeedsBadging.indexOfKey(userId);
22582        if (index < 0) {
22583            final UserInfo userInfo;
22584            final long token = Binder.clearCallingIdentity();
22585            try {
22586                userInfo = sUserManager.getUserInfo(userId);
22587            } finally {
22588                Binder.restoreCallingIdentity(token);
22589            }
22590            final boolean b;
22591            if (userInfo != null && userInfo.isManagedProfile()) {
22592                b = true;
22593            } else {
22594                b = false;
22595            }
22596            mUserNeedsBadging.put(userId, b);
22597            return b;
22598        }
22599        return mUserNeedsBadging.valueAt(index);
22600    }
22601
22602    @Override
22603    public KeySet getKeySetByAlias(String packageName, String alias) {
22604        if (packageName == null || alias == null) {
22605            return null;
22606        }
22607        synchronized(mPackages) {
22608            final PackageParser.Package pkg = mPackages.get(packageName);
22609            if (pkg == null) {
22610                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22611                throw new IllegalArgumentException("Unknown package: " + packageName);
22612            }
22613            final PackageSetting ps = (PackageSetting) pkg.mExtras;
22614            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
22615                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
22616                throw new IllegalArgumentException("Unknown package: " + packageName);
22617            }
22618            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
22619            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22620        }
22621    }
22622
22623    @Override
22624    public KeySet getSigningKeySet(String packageName) {
22625        if (packageName == null) {
22626            return null;
22627        }
22628        synchronized(mPackages) {
22629            final int callingUid = Binder.getCallingUid();
22630            final int callingUserId = UserHandle.getUserId(callingUid);
22631            final PackageParser.Package pkg = mPackages.get(packageName);
22632            if (pkg == null) {
22633                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22634                throw new IllegalArgumentException("Unknown package: " + packageName);
22635            }
22636            final PackageSetting ps = (PackageSetting) pkg.mExtras;
22637            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
22638                // filter and pretend the package doesn't exist
22639                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
22640                        + ", uid:" + callingUid);
22641                throw new IllegalArgumentException("Unknown package: " + packageName);
22642            }
22643            if (pkg.applicationInfo.uid != callingUid
22644                    && Process.SYSTEM_UID != callingUid) {
22645                throw new SecurityException("May not access signing KeySet of other apps.");
22646            }
22647            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
22648            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
22649        }
22650    }
22651
22652    @Override
22653    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
22654        final int callingUid = Binder.getCallingUid();
22655        if (getInstantAppPackageName(callingUid) != null) {
22656            return false;
22657        }
22658        if (packageName == null || ks == null) {
22659            return false;
22660        }
22661        synchronized(mPackages) {
22662            final PackageParser.Package pkg = mPackages.get(packageName);
22663            if (pkg == null
22664                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
22665                            UserHandle.getUserId(callingUid))) {
22666                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22667                throw new IllegalArgumentException("Unknown package: " + packageName);
22668            }
22669            IBinder ksh = ks.getToken();
22670            if (ksh instanceof KeySetHandle) {
22671                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
22672                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
22673            }
22674            return false;
22675        }
22676    }
22677
22678    @Override
22679    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
22680        final int callingUid = Binder.getCallingUid();
22681        if (getInstantAppPackageName(callingUid) != null) {
22682            return false;
22683        }
22684        if (packageName == null || ks == null) {
22685            return false;
22686        }
22687        synchronized(mPackages) {
22688            final PackageParser.Package pkg = mPackages.get(packageName);
22689            if (pkg == null
22690                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
22691                            UserHandle.getUserId(callingUid))) {
22692                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22693                throw new IllegalArgumentException("Unknown package: " + packageName);
22694            }
22695            IBinder ksh = ks.getToken();
22696            if (ksh instanceof KeySetHandle) {
22697                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
22698                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
22699            }
22700            return false;
22701        }
22702    }
22703
22704    private void deletePackageIfUnusedLPr(final String packageName) {
22705        PackageSetting ps = mSettings.mPackages.get(packageName);
22706        if (ps == null) {
22707            return;
22708        }
22709        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
22710            // TODO Implement atomic delete if package is unused
22711            // It is currently possible that the package will be deleted even if it is installed
22712            // after this method returns.
22713            mHandler.post(new Runnable() {
22714                public void run() {
22715                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22716                            0, PackageManager.DELETE_ALL_USERS);
22717                }
22718            });
22719        }
22720    }
22721
22722    /**
22723     * Check and throw if the given before/after packages would be considered a
22724     * downgrade.
22725     */
22726    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
22727            throws PackageManagerException {
22728        if (after.getLongVersionCode() < before.getLongVersionCode()) {
22729            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22730                    "Update version code " + after.versionCode + " is older than current "
22731                    + before.getLongVersionCode());
22732        } else if (after.getLongVersionCode() == before.getLongVersionCode()) {
22733            if (after.baseRevisionCode < before.baseRevisionCode) {
22734                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22735                        "Update base revision code " + after.baseRevisionCode
22736                        + " is older than current " + before.baseRevisionCode);
22737            }
22738
22739            if (!ArrayUtils.isEmpty(after.splitNames)) {
22740                for (int i = 0; i < after.splitNames.length; i++) {
22741                    final String splitName = after.splitNames[i];
22742                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
22743                    if (j != -1) {
22744                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
22745                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22746                                    "Update split " + splitName + " revision code "
22747                                    + after.splitRevisionCodes[i] + " is older than current "
22748                                    + before.splitRevisionCodes[j]);
22749                        }
22750                    }
22751                }
22752            }
22753        }
22754    }
22755
22756    private static class MoveCallbacks extends Handler {
22757        private static final int MSG_CREATED = 1;
22758        private static final int MSG_STATUS_CHANGED = 2;
22759
22760        private final RemoteCallbackList<IPackageMoveObserver>
22761                mCallbacks = new RemoteCallbackList<>();
22762
22763        private final SparseIntArray mLastStatus = new SparseIntArray();
22764
22765        public MoveCallbacks(Looper looper) {
22766            super(looper);
22767        }
22768
22769        public void register(IPackageMoveObserver callback) {
22770            mCallbacks.register(callback);
22771        }
22772
22773        public void unregister(IPackageMoveObserver callback) {
22774            mCallbacks.unregister(callback);
22775        }
22776
22777        @Override
22778        public void handleMessage(Message msg) {
22779            final SomeArgs args = (SomeArgs) msg.obj;
22780            final int n = mCallbacks.beginBroadcast();
22781            for (int i = 0; i < n; i++) {
22782                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
22783                try {
22784                    invokeCallback(callback, msg.what, args);
22785                } catch (RemoteException ignored) {
22786                }
22787            }
22788            mCallbacks.finishBroadcast();
22789            args.recycle();
22790        }
22791
22792        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
22793                throws RemoteException {
22794            switch (what) {
22795                case MSG_CREATED: {
22796                    callback.onCreated(args.argi1, (Bundle) args.arg2);
22797                    break;
22798                }
22799                case MSG_STATUS_CHANGED: {
22800                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
22801                    break;
22802                }
22803            }
22804        }
22805
22806        private void notifyCreated(int moveId, Bundle extras) {
22807            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
22808
22809            final SomeArgs args = SomeArgs.obtain();
22810            args.argi1 = moveId;
22811            args.arg2 = extras;
22812            obtainMessage(MSG_CREATED, args).sendToTarget();
22813        }
22814
22815        private void notifyStatusChanged(int moveId, int status) {
22816            notifyStatusChanged(moveId, status, -1);
22817        }
22818
22819        private void notifyStatusChanged(int moveId, int status, long estMillis) {
22820            Slog.v(TAG, "Move " + moveId + " status " + status);
22821
22822            final SomeArgs args = SomeArgs.obtain();
22823            args.argi1 = moveId;
22824            args.argi2 = status;
22825            args.arg3 = estMillis;
22826            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
22827
22828            synchronized (mLastStatus) {
22829                mLastStatus.put(moveId, status);
22830            }
22831        }
22832    }
22833
22834    private final static class OnPermissionChangeListeners extends Handler {
22835        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
22836
22837        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
22838                new RemoteCallbackList<>();
22839
22840        public OnPermissionChangeListeners(Looper looper) {
22841            super(looper);
22842        }
22843
22844        @Override
22845        public void handleMessage(Message msg) {
22846            switch (msg.what) {
22847                case MSG_ON_PERMISSIONS_CHANGED: {
22848                    final int uid = msg.arg1;
22849                    handleOnPermissionsChanged(uid);
22850                } break;
22851            }
22852        }
22853
22854        public void addListenerLocked(IOnPermissionsChangeListener listener) {
22855            mPermissionListeners.register(listener);
22856
22857        }
22858
22859        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
22860            mPermissionListeners.unregister(listener);
22861        }
22862
22863        public void onPermissionsChanged(int uid) {
22864            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
22865                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
22866            }
22867        }
22868
22869        private void handleOnPermissionsChanged(int uid) {
22870            final int count = mPermissionListeners.beginBroadcast();
22871            try {
22872                for (int i = 0; i < count; i++) {
22873                    IOnPermissionsChangeListener callback = mPermissionListeners
22874                            .getBroadcastItem(i);
22875                    try {
22876                        callback.onPermissionsChanged(uid);
22877                    } catch (RemoteException e) {
22878                        Log.e(TAG, "Permission listener is dead", e);
22879                    }
22880                }
22881            } finally {
22882                mPermissionListeners.finishBroadcast();
22883            }
22884        }
22885    }
22886
22887    private class PackageManagerNative extends IPackageManagerNative.Stub {
22888        @Override
22889        public String[] getNamesForUids(int[] uids) throws RemoteException {
22890            final String[] results = PackageManagerService.this.getNamesForUids(uids);
22891            // massage results so they can be parsed by the native binder
22892            for (int i = results.length - 1; i >= 0; --i) {
22893                if (results[i] == null) {
22894                    results[i] = "";
22895                }
22896            }
22897            return results;
22898        }
22899
22900        // NB: this differentiates between preloads and sideloads
22901        @Override
22902        public String getInstallerForPackage(String packageName) throws RemoteException {
22903            final String installerName = getInstallerPackageName(packageName);
22904            if (!TextUtils.isEmpty(installerName)) {
22905                return installerName;
22906            }
22907            // differentiate between preload and sideload
22908            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
22909            ApplicationInfo appInfo = getApplicationInfo(packageName,
22910                                    /*flags*/ 0,
22911                                    /*userId*/ callingUser);
22912            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22913                return "preload";
22914            }
22915            return "";
22916        }
22917
22918        @Override
22919        public long getVersionCodeForPackage(String packageName) throws RemoteException {
22920            try {
22921                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
22922                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
22923                if (pInfo != null) {
22924                    return pInfo.getLongVersionCode();
22925                }
22926            } catch (Exception e) {
22927            }
22928            return 0;
22929        }
22930    }
22931
22932    private class PackageManagerInternalImpl extends PackageManagerInternal {
22933        @Override
22934        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
22935                int flagValues, int userId) {
22936            PackageManagerService.this.updatePermissionFlags(
22937                    permName, packageName, flagMask, flagValues, userId);
22938        }
22939
22940        @Override
22941        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
22942            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
22943        }
22944
22945        @Override
22946        public boolean isInstantApp(String packageName, int userId) {
22947            return PackageManagerService.this.isInstantApp(packageName, userId);
22948        }
22949
22950        @Override
22951        public String getInstantAppPackageName(int uid) {
22952            return PackageManagerService.this.getInstantAppPackageName(uid);
22953        }
22954
22955        @Override
22956        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
22957            synchronized (mPackages) {
22958                return PackageManagerService.this.filterAppAccessLPr(
22959                        (PackageSetting) pkg.mExtras, callingUid, userId);
22960            }
22961        }
22962
22963        @Override
22964        public PackageParser.Package getPackage(String packageName) {
22965            synchronized (mPackages) {
22966                packageName = resolveInternalPackageNameLPr(
22967                        packageName, PackageManager.VERSION_CODE_HIGHEST);
22968                return mPackages.get(packageName);
22969            }
22970        }
22971
22972        @Override
22973        public PackageList getPackageList(PackageListObserver observer) {
22974            synchronized (mPackages) {
22975                final int N = mPackages.size();
22976                final ArrayList<String> list = new ArrayList<>(N);
22977                for (int i = 0; i < N; i++) {
22978                    list.add(mPackages.keyAt(i));
22979                }
22980                final PackageList packageList = new PackageList(list, observer);
22981                if (observer != null) {
22982                    mPackageListObservers.add(packageList);
22983                }
22984                return packageList;
22985            }
22986        }
22987
22988        @Override
22989        public void removePackageListObserver(PackageListObserver observer) {
22990            synchronized (mPackages) {
22991                mPackageListObservers.remove(observer);
22992            }
22993        }
22994
22995        @Override
22996        public PackageParser.Package getDisabledPackage(String packageName) {
22997            synchronized (mPackages) {
22998                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
22999                return (ps != null) ? ps.pkg : null;
23000            }
23001        }
23002
23003        @Override
23004        public String getKnownPackageName(int knownPackage, int userId) {
23005            switch(knownPackage) {
23006                case PackageManagerInternal.PACKAGE_BROWSER:
23007                    return getDefaultBrowserPackageName(userId);
23008                case PackageManagerInternal.PACKAGE_INSTALLER:
23009                    return mRequiredInstallerPackage;
23010                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
23011                    return mSetupWizardPackage;
23012                case PackageManagerInternal.PACKAGE_SYSTEM:
23013                    return "android";
23014                case PackageManagerInternal.PACKAGE_VERIFIER:
23015                    return mRequiredVerifierPackage;
23016            }
23017            return null;
23018        }
23019
23020        @Override
23021        public boolean isResolveActivityComponent(ComponentInfo component) {
23022            return mResolveActivity.packageName.equals(component.packageName)
23023                    && mResolveActivity.name.equals(component.name);
23024        }
23025
23026        @Override
23027        public void setLocationPackagesProvider(PackagesProvider provider) {
23028            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
23029        }
23030
23031        @Override
23032        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23033            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
23034        }
23035
23036        @Override
23037        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23038            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
23039        }
23040
23041        @Override
23042        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23043            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
23044        }
23045
23046        @Override
23047        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23048            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
23049        }
23050
23051        @Override
23052        public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) {
23053            mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider);
23054        }
23055
23056        @Override
23057        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23058            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
23059        }
23060
23061        @Override
23062        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23063            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
23064        }
23065
23066        @Override
23067        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23068            synchronized (mPackages) {
23069                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23070            }
23071            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
23072        }
23073
23074        @Override
23075        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23076            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
23077                    packageName, userId);
23078        }
23079
23080        @Override
23081        public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) {
23082            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp(
23083                    packageName, userId);
23084        }
23085
23086        @Override
23087        public void setKeepUninstalledPackages(final List<String> packageList) {
23088            Preconditions.checkNotNull(packageList);
23089            List<String> removedFromList = null;
23090            synchronized (mPackages) {
23091                if (mKeepUninstalledPackages != null) {
23092                    final int packagesCount = mKeepUninstalledPackages.size();
23093                    for (int i = 0; i < packagesCount; i++) {
23094                        String oldPackage = mKeepUninstalledPackages.get(i);
23095                        if (packageList != null && packageList.contains(oldPackage)) {
23096                            continue;
23097                        }
23098                        if (removedFromList == null) {
23099                            removedFromList = new ArrayList<>();
23100                        }
23101                        removedFromList.add(oldPackage);
23102                    }
23103                }
23104                mKeepUninstalledPackages = new ArrayList<>(packageList);
23105                if (removedFromList != null) {
23106                    final int removedCount = removedFromList.size();
23107                    for (int i = 0; i < removedCount; i++) {
23108                        deletePackageIfUnusedLPr(removedFromList.get(i));
23109                    }
23110                }
23111            }
23112        }
23113
23114        @Override
23115        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23116            synchronized (mPackages) {
23117                return mPermissionManager.isPermissionsReviewRequired(
23118                        mPackages.get(packageName), userId);
23119            }
23120        }
23121
23122        @Override
23123        public PackageInfo getPackageInfo(
23124                String packageName, int flags, int filterCallingUid, int userId) {
23125            return PackageManagerService.this
23126                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
23127                            flags, filterCallingUid, userId);
23128        }
23129
23130        @Override
23131        public int getPackageUid(String packageName, int flags, int userId) {
23132            return PackageManagerService.this
23133                    .getPackageUid(packageName, flags, userId);
23134        }
23135
23136        @Override
23137        public ApplicationInfo getApplicationInfo(
23138                String packageName, int flags, int filterCallingUid, int userId) {
23139            return PackageManagerService.this
23140                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
23141        }
23142
23143        @Override
23144        public ActivityInfo getActivityInfo(
23145                ComponentName component, int flags, int filterCallingUid, int userId) {
23146            return PackageManagerService.this
23147                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
23148        }
23149
23150        @Override
23151        public List<ResolveInfo> queryIntentActivities(
23152                Intent intent, int flags, int filterCallingUid, int userId) {
23153            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23154            return PackageManagerService.this
23155                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
23156                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
23157        }
23158
23159        @Override
23160        public List<ResolveInfo> queryIntentServices(
23161                Intent intent, int flags, int callingUid, int userId) {
23162            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23163            return PackageManagerService.this
23164                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
23165                            false);
23166        }
23167
23168        @Override
23169        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23170                int userId) {
23171            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23172        }
23173
23174        @Override
23175        public void setDeviceAndProfileOwnerPackages(
23176                int deviceOwnerUserId, String deviceOwnerPackage,
23177                SparseArray<String> profileOwnerPackages) {
23178            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23179                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23180        }
23181
23182        @Override
23183        public boolean isPackageDataProtected(int userId, String packageName) {
23184            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23185        }
23186
23187        @Override
23188        public boolean isPackageEphemeral(int userId, String packageName) {
23189            synchronized (mPackages) {
23190                final PackageSetting ps = mSettings.mPackages.get(packageName);
23191                return ps != null ? ps.getInstantApp(userId) : false;
23192            }
23193        }
23194
23195        @Override
23196        public boolean wasPackageEverLaunched(String packageName, int userId) {
23197            synchronized (mPackages) {
23198                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23199            }
23200        }
23201
23202        @Override
23203        public void grantRuntimePermission(String packageName, String permName, int userId,
23204                boolean overridePolicy) {
23205            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
23206                    permName, packageName, overridePolicy, getCallingUid(), userId,
23207                    mPermissionCallback);
23208        }
23209
23210        @Override
23211        public void revokeRuntimePermission(String packageName, String permName, int userId,
23212                boolean overridePolicy) {
23213            mPermissionManager.revokeRuntimePermission(
23214                    permName, packageName, overridePolicy, getCallingUid(), userId,
23215                    mPermissionCallback);
23216        }
23217
23218        @Override
23219        public String getNameForUid(int uid) {
23220            return PackageManagerService.this.getNameForUid(uid);
23221        }
23222
23223        @Override
23224        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23225                Intent origIntent, String resolvedType, String callingPackage,
23226                Bundle verificationBundle, int userId) {
23227            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23228                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
23229                    userId);
23230        }
23231
23232        @Override
23233        public void grantEphemeralAccess(int userId, Intent intent,
23234                int targetAppId, int ephemeralAppId) {
23235            synchronized (mPackages) {
23236                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23237                        targetAppId, ephemeralAppId);
23238            }
23239        }
23240
23241        @Override
23242        public boolean isInstantAppInstallerComponent(ComponentName component) {
23243            synchronized (mPackages) {
23244                return mInstantAppInstallerActivity != null
23245                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23246            }
23247        }
23248
23249        @Override
23250        public void pruneInstantApps() {
23251            mInstantAppRegistry.pruneInstantApps();
23252        }
23253
23254        @Override
23255        public String getSetupWizardPackageName() {
23256            return mSetupWizardPackage;
23257        }
23258
23259        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23260            if (policy != null) {
23261                mExternalSourcesPolicy = policy;
23262            }
23263        }
23264
23265        @Override
23266        public boolean isPackagePersistent(String packageName) {
23267            synchronized (mPackages) {
23268                PackageParser.Package pkg = mPackages.get(packageName);
23269                return pkg != null
23270                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23271                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23272                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23273                        : false;
23274            }
23275        }
23276
23277        @Override
23278        public boolean isLegacySystemApp(Package pkg) {
23279            synchronized (mPackages) {
23280                final PackageSetting ps = (PackageSetting) pkg.mExtras;
23281                return mPromoteSystemApps
23282                        && ps.isSystem()
23283                        && mExistingSystemPackages.contains(ps.name);
23284            }
23285        }
23286
23287        @Override
23288        public List<PackageInfo> getOverlayPackages(int userId) {
23289            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23290            synchronized (mPackages) {
23291                for (PackageParser.Package p : mPackages.values()) {
23292                    if (p.mOverlayTarget != null) {
23293                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23294                        if (pkg != null) {
23295                            overlayPackages.add(pkg);
23296                        }
23297                    }
23298                }
23299            }
23300            return overlayPackages;
23301        }
23302
23303        @Override
23304        public List<String> getTargetPackageNames(int userId) {
23305            List<String> targetPackages = new ArrayList<>();
23306            synchronized (mPackages) {
23307                for (PackageParser.Package p : mPackages.values()) {
23308                    if (p.mOverlayTarget == null) {
23309                        targetPackages.add(p.packageName);
23310                    }
23311                }
23312            }
23313            return targetPackages;
23314        }
23315
23316        @Override
23317        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23318                @Nullable List<String> overlayPackageNames) {
23319            synchronized (mPackages) {
23320                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23321                    Slog.e(TAG, "failed to find package " + targetPackageName);
23322                    return false;
23323                }
23324                ArrayList<String> overlayPaths = null;
23325                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
23326                    final int N = overlayPackageNames.size();
23327                    overlayPaths = new ArrayList<>(N);
23328                    for (int i = 0; i < N; i++) {
23329                        final String packageName = overlayPackageNames.get(i);
23330                        final PackageParser.Package pkg = mPackages.get(packageName);
23331                        if (pkg == null) {
23332                            Slog.e(TAG, "failed to find package " + packageName);
23333                            return false;
23334                        }
23335                        overlayPaths.add(pkg.baseCodePath);
23336                    }
23337                }
23338
23339                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
23340                ps.setOverlayPaths(overlayPaths, userId);
23341                return true;
23342            }
23343        }
23344
23345        @Override
23346        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23347                int flags, int userId, boolean resolveForStart) {
23348            return resolveIntentInternal(
23349                    intent, resolvedType, flags, userId, resolveForStart);
23350        }
23351
23352        @Override
23353        public ResolveInfo resolveService(Intent intent, String resolvedType,
23354                int flags, int userId, int callingUid) {
23355            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
23356        }
23357
23358        @Override
23359        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
23360            return PackageManagerService.this.resolveContentProviderInternal(
23361                    name, flags, userId);
23362        }
23363
23364        @Override
23365        public void addIsolatedUid(int isolatedUid, int ownerUid) {
23366            synchronized (mPackages) {
23367                mIsolatedOwners.put(isolatedUid, ownerUid);
23368            }
23369        }
23370
23371        @Override
23372        public void removeIsolatedUid(int isolatedUid) {
23373            synchronized (mPackages) {
23374                mIsolatedOwners.delete(isolatedUid);
23375            }
23376        }
23377
23378        @Override
23379        public int getUidTargetSdkVersion(int uid) {
23380            synchronized (mPackages) {
23381                return getUidTargetSdkVersionLockedLPr(uid);
23382            }
23383        }
23384
23385        @Override
23386        public boolean canAccessInstantApps(int callingUid, int userId) {
23387            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
23388        }
23389
23390        @Override
23391        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
23392            synchronized (mPackages) {
23393                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
23394            }
23395        }
23396
23397        @Override
23398        public void notifyPackageUse(String packageName, int reason) {
23399            synchronized (mPackages) {
23400                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
23401            }
23402        }
23403    }
23404
23405    @Override
23406    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23407        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23408        synchronized (mPackages) {
23409            final long identity = Binder.clearCallingIdentity();
23410            try {
23411                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
23412                        packageNames, userId);
23413            } finally {
23414                Binder.restoreCallingIdentity(identity);
23415            }
23416        }
23417    }
23418
23419    @Override
23420    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23421        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23422        synchronized (mPackages) {
23423            final long identity = Binder.clearCallingIdentity();
23424            try {
23425                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
23426                        packageNames, userId);
23427            } finally {
23428                Binder.restoreCallingIdentity(identity);
23429            }
23430        }
23431    }
23432
23433    private static void enforceSystemOrPhoneCaller(String tag) {
23434        int callingUid = Binder.getCallingUid();
23435        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23436            throw new SecurityException(
23437                    "Cannot call " + tag + " from UID " + callingUid);
23438        }
23439    }
23440
23441    boolean isHistoricalPackageUsageAvailable() {
23442        return mPackageUsage.isHistoricalPackageUsageAvailable();
23443    }
23444
23445    /**
23446     * Return a <b>copy</b> of the collection of packages known to the package manager.
23447     * @return A copy of the values of mPackages.
23448     */
23449    Collection<PackageParser.Package> getPackages() {
23450        synchronized (mPackages) {
23451            return new ArrayList<>(mPackages.values());
23452        }
23453    }
23454
23455    /**
23456     * Logs process start information (including base APK hash) to the security log.
23457     * @hide
23458     */
23459    @Override
23460    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23461            String apkFile, int pid) {
23462        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23463            return;
23464        }
23465        if (!SecurityLog.isLoggingEnabled()) {
23466            return;
23467        }
23468        Bundle data = new Bundle();
23469        data.putLong("startTimestamp", System.currentTimeMillis());
23470        data.putString("processName", processName);
23471        data.putInt("uid", uid);
23472        data.putString("seinfo", seinfo);
23473        data.putString("apkFile", apkFile);
23474        data.putInt("pid", pid);
23475        Message msg = mProcessLoggingHandler.obtainMessage(
23476                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23477        msg.setData(data);
23478        mProcessLoggingHandler.sendMessage(msg);
23479    }
23480
23481    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23482        return mCompilerStats.getPackageStats(pkgName);
23483    }
23484
23485    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23486        return getOrCreateCompilerPackageStats(pkg.packageName);
23487    }
23488
23489    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23490        return mCompilerStats.getOrCreatePackageStats(pkgName);
23491    }
23492
23493    public void deleteCompilerPackageStats(String pkgName) {
23494        mCompilerStats.deletePackageStats(pkgName);
23495    }
23496
23497    @Override
23498    public int getInstallReason(String packageName, int userId) {
23499        final int callingUid = Binder.getCallingUid();
23500        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
23501                true /* requireFullPermission */, false /* checkShell */,
23502                "get install reason");
23503        synchronized (mPackages) {
23504            final PackageSetting ps = mSettings.mPackages.get(packageName);
23505            if (filterAppAccessLPr(ps, callingUid, userId)) {
23506                return PackageManager.INSTALL_REASON_UNKNOWN;
23507            }
23508            if (ps != null) {
23509                return ps.getInstallReason(userId);
23510            }
23511        }
23512        return PackageManager.INSTALL_REASON_UNKNOWN;
23513    }
23514
23515    @Override
23516    public boolean canRequestPackageInstalls(String packageName, int userId) {
23517        return canRequestPackageInstallsInternal(packageName, 0, userId,
23518                true /* throwIfPermNotDeclared*/);
23519    }
23520
23521    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
23522            boolean throwIfPermNotDeclared) {
23523        int callingUid = Binder.getCallingUid();
23524        int uid = getPackageUid(packageName, 0, userId);
23525        if (callingUid != uid && callingUid != Process.ROOT_UID
23526                && callingUid != Process.SYSTEM_UID) {
23527            throw new SecurityException(
23528                    "Caller uid " + callingUid + " does not own package " + packageName);
23529        }
23530        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
23531        if (info == null) {
23532            return false;
23533        }
23534        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23535            return false;
23536        }
23537        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23538        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23539        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23540            if (throwIfPermNotDeclared) {
23541                throw new SecurityException("Need to declare " + appOpPermission
23542                        + " to call this api");
23543            } else {
23544                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
23545                return false;
23546            }
23547        }
23548        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23549            return false;
23550        }
23551        if (mExternalSourcesPolicy != null) {
23552            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23553            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23554                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23555            }
23556        }
23557        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23558    }
23559
23560    @Override
23561    public ComponentName getInstantAppResolverSettingsComponent() {
23562        return mInstantAppResolverSettingsComponent;
23563    }
23564
23565    @Override
23566    public ComponentName getInstantAppInstallerComponent() {
23567        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23568            return null;
23569        }
23570        return mInstantAppInstallerActivity == null
23571                ? null : mInstantAppInstallerActivity.getComponentName();
23572    }
23573
23574    @Override
23575    public String getInstantAppAndroidId(String packageName, int userId) {
23576        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
23577                "getInstantAppAndroidId");
23578        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
23579                true /* requireFullPermission */, false /* checkShell */,
23580                "getInstantAppAndroidId");
23581        // Make sure the target is an Instant App.
23582        if (!isInstantApp(packageName, userId)) {
23583            return null;
23584        }
23585        synchronized (mPackages) {
23586            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
23587        }
23588    }
23589
23590    boolean canHaveOatDir(String packageName) {
23591        synchronized (mPackages) {
23592            PackageParser.Package p = mPackages.get(packageName);
23593            if (p == null) {
23594                return false;
23595            }
23596            return p.canHaveOatDir();
23597        }
23598    }
23599
23600    private String getOatDir(PackageParser.Package pkg) {
23601        if (!pkg.canHaveOatDir()) {
23602            return null;
23603        }
23604        File codePath = new File(pkg.codePath);
23605        if (codePath.isDirectory()) {
23606            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
23607        }
23608        return null;
23609    }
23610
23611    void deleteOatArtifactsOfPackage(String packageName) {
23612        final String[] instructionSets;
23613        final List<String> codePaths;
23614        final String oatDir;
23615        final PackageParser.Package pkg;
23616        synchronized (mPackages) {
23617            pkg = mPackages.get(packageName);
23618        }
23619        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
23620        codePaths = pkg.getAllCodePaths();
23621        oatDir = getOatDir(pkg);
23622
23623        for (String codePath : codePaths) {
23624            for (String isa : instructionSets) {
23625                try {
23626                    mInstaller.deleteOdex(codePath, isa, oatDir);
23627                } catch (InstallerException e) {
23628                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
23629                }
23630            }
23631        }
23632    }
23633
23634    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
23635        Set<String> unusedPackages = new HashSet<>();
23636        long currentTimeInMillis = System.currentTimeMillis();
23637        synchronized (mPackages) {
23638            for (PackageParser.Package pkg : mPackages.values()) {
23639                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
23640                if (ps == null) {
23641                    continue;
23642                }
23643                PackageDexUsage.PackageUseInfo packageUseInfo =
23644                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
23645                if (PackageManagerServiceUtils
23646                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
23647                                downgradeTimeThresholdMillis, packageUseInfo,
23648                                pkg.getLatestPackageUseTimeInMills(),
23649                                pkg.getLatestForegroundPackageUseTimeInMills())) {
23650                    unusedPackages.add(pkg.packageName);
23651                }
23652            }
23653        }
23654        return unusedPackages;
23655    }
23656}
23657
23658interface PackageSender {
23659    /**
23660     * @param userIds User IDs where the action occurred on a full application
23661     * @param instantUserIds User IDs where the action occurred on an instant application
23662     */
23663    void sendPackageBroadcast(final String action, final String pkg,
23664        final Bundle extras, final int flags, final String targetPkg,
23665        final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds);
23666    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
23667        boolean includeStopped, int appId, int[] userIds, int[] instantUserIds);
23668    void notifyPackageAdded(String packageName);
23669    void notifyPackageRemoved(String packageName);
23670}
23671